home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung 2 / Power-Programmierung CD 2 (Tewi)(1994).iso / gnu / gnulib / dkbtrace / pbmplus / source / libtiff / tif_dir.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-23  |  69.7 KB  |  2,472 lines

  1. #ifndef lint
  2. static char rcsid[] = "$Header: /usr/people/sam/tiff/libtiff/RCS/tif_dir.c,v 1.86 91/08/19 14:40:43 sam Exp $";
  3. #endif
  4.  
  5. /*
  6.  * Copyright (c) 1988, 1989, 1990, 1991 Sam Leffler
  7.  * Copyright (c) 1991 Silicon Graphics, Inc.
  8.  *
  9.  * Permission to use, copy, modify, distribute, and sell this software and 
  10.  * its documentation for any purpose is hereby granted without fee, provided
  11.  * that (i) the above copyright notices and this permission notice appear in
  12.  * all copies of the software and related documentation, and (ii) the names of
  13.  * Sam Leffler and Silicon Graphics may not be used in any advertising or
  14.  * publicity relating to the software without the specific, prior written
  15.  * permission of Sam Leffler and Silicon Graphics.
  16.  * 
  17.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
  18.  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
  19.  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
  20.  * 
  21.  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  22.  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  23.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  24.  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
  25.  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  26.  * OF THIS SOFTWARE.
  27.  */
  28.  
  29. /*
  30.  * TIFF Library.
  31.  *
  32.  * Directory Support Routines.
  33.  *
  34.  * NB: Beware of the varargs declarations for routines in
  35.  *     this file.  The names and types of variables has been
  36.  *     carefully chosen to make things work with compilers that
  37.  *     are busted in one way or another (e.g. SGI/MIPS).
  38.  */
  39. #include "tiffioP.h"
  40.  
  41. #ifndef TRUE
  42. #define    TRUE    1
  43. #define    FALSE    0
  44. #endif
  45. #define    TIFF_ANY    TIFF_NOTYPE
  46.  
  47. #define    NITEMS(a)    (sizeof (a) / sizeof  (a[0]))
  48.  
  49. #define    FieldSet(fields, f)        (fields[f/32] & (1L<<(f&0x1f)))
  50. #define    ResetFieldBit(fields, f)    (fields[f/32] &= ~(1L<<(f&0x1f)))
  51.  
  52. #define    TIFFExtractData(tif, type, v) \
  53.     ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \
  54.         ((v) >> (tif)->tif_typeshift[type]) & (tif)->tif_typemask[type] : \
  55.     (v) & (tif)->tif_typemask[type])
  56. #define    TIFFInsertData(tif, type, v) \
  57.     ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \
  58.         ((v) & (tif)->tif_typemask[type]) << (tif)->tif_typeshift[type] : \
  59.     (v) & (tif)->tif_typemask[type])
  60.  
  61. typedef    struct {
  62.     u_short    field_tag;        /* field's tag */
  63.     short    field_count;        /* write count (-1 for unknown) */
  64.     TIFFDataType field_type;    /* type of associated data */
  65.     u_short    field_bit;        /* bit in fieldsset bit vector */
  66.     u_short    field_oktochange;    /* if true, can change while writing */
  67.     char    *field_name;        /* ASCII name */
  68. } TIFFFieldInfo;
  69.  
  70. /*
  71.  * NB: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG.
  72.  *     Also, if a tag can have both LONG and SHORT types
  73.  *     then the LONG must be placed before the SHORT.
  74.  */
  75. static    TIFFFieldInfo FieldInfo[] = {
  76.     { TIFFTAG_SUBFILETYPE,     1, TIFF_LONG,    FIELD_SUBFILETYPE,
  77.       TRUE,    "SubfileType" },
  78. #ifdef SUBFILE_COMPAT
  79.     { TIFFTAG_SUBFILETYPE,     1, TIFF_SHORT,    FIELD_SUBFILETYPE,
  80.       FALSE,    "SubfileType" },
  81. #endif
  82.     { TIFFTAG_OSUBFILETYPE,     1, TIFF_SHORT,    FIELD_SUBFILETYPE,
  83.       FALSE,    "OldSubfileType" },
  84.     { TIFFTAG_IMAGEWIDTH,     1, TIFF_LONG,    FIELD_IMAGEDIMENSIONS,
  85.       FALSE,    "ImageWidth" },
  86.     { TIFFTAG_IMAGEWIDTH,     1, TIFF_SHORT,    FIELD_IMAGEDIMENSIONS,
  87.       FALSE,    "ImageWidth" },
  88.     { TIFFTAG_IMAGELENGTH,     1, TIFF_LONG,    FIELD_IMAGEDIMENSIONS,
  89.       TRUE,    "ImageLength" },
  90.     { TIFFTAG_IMAGELENGTH,     1, TIFF_SHORT,    FIELD_IMAGEDIMENSIONS,
  91.       TRUE,    "ImageLength" },
  92.     { TIFFTAG_BITSPERSAMPLE,    -1, TIFF_SHORT,    FIELD_BITSPERSAMPLE,
  93.       FALSE,    "BitsPerSample" },
  94.     { TIFFTAG_COMPRESSION,     1, TIFF_SHORT,    FIELD_COMPRESSION,
  95.       FALSE,    "Compression" },
  96.     { TIFFTAG_PHOTOMETRIC,     1, TIFF_SHORT,    FIELD_PHOTOMETRIC,
  97.       TRUE,    "PhotometricInterpretation" },
  98.     { TIFFTAG_THRESHHOLDING,     1, TIFF_SHORT,    FIELD_THRESHHOLDING,
  99.       TRUE,    "Threshholding" },
  100.     { TIFFTAG_CELLWIDTH,     1, TIFF_SHORT,    (u_short)-1,
  101.       TRUE,    "CellWidth" },
  102.     { TIFFTAG_CELLLENGTH,     1, TIFF_SHORT,    (u_short)-1,
  103.       TRUE,    "CellLength" },
  104.     { TIFFTAG_FILLORDER,     1, TIFF_SHORT,    FIELD_FILLORDER,
  105.       FALSE,    "FillOrder" },
  106.     { TIFFTAG_DOCUMENTNAME,    -1, TIFF_ASCII,    FIELD_DOCUMENTNAME,
  107.       TRUE,    "DocumentName" },
  108.     { TIFFTAG_IMAGEDESCRIPTION,    -1, TIFF_ASCII,    FIELD_IMAGEDESCRIPTION,
  109.       TRUE,    "ImageDescription" },
  110.     { TIFFTAG_MAKE,        -1, TIFF_ASCII,    FIELD_MAKE,
  111.       TRUE,    "Make" },
  112.     { TIFFTAG_MODEL,        -1, TIFF_ASCII,    FIELD_MODEL,
  113.       TRUE,    "Model" },
  114.     { TIFFTAG_STRIPOFFSETS,    -1, TIFF_LONG,    FIELD_STRIPOFFSETS,
  115.       FALSE,    "StripOffsets" },
  116.     { TIFFTAG_STRIPOFFSETS,    -1, TIFF_SHORT,    FIELD_STRIPOFFSETS,
  117.       FALSE,    "StripOffsets" },
  118.     { TIFFTAG_ORIENTATION,     1, TIFF_SHORT,    FIELD_ORIENTATION,
  119.       TRUE,    "Orientation" },
  120.     { TIFFTAG_SAMPLESPERPIXEL,     1, TIFF_SHORT,    FIELD_SAMPLESPERPIXEL,
  121.       FALSE,    "SamplesPerPixel" },
  122.     { TIFFTAG_ROWSPERSTRIP,     1, TIFF_LONG,    FIELD_ROWSPERSTRIP,
  123.       FALSE,    "RowsPerStrip" },
  124.     { TIFFTAG_ROWSPERSTRIP,     1, TIFF_SHORT,    FIELD_ROWSPERSTRIP,
  125.       FALSE,    "RowsPerStrip" },
  126.     { TIFFTAG_STRIPBYTECOUNTS,    -1, TIFF_LONG,    FIELD_STRIPBYTECOUNTS,
  127.       FALSE,    "StripByteCounts" },
  128.     { TIFFTAG_STRIPBYTECOUNTS,    -1, TIFF_SHORT,    FIELD_STRIPBYTECOUNTS,
  129.       FALSE,    "StripByteCounts" },
  130.     { TIFFTAG_MINSAMPLEVALUE,    -1, TIFF_SHORT,    FIELD_MINSAMPLEVALUE,
  131.       TRUE,    "MinSampleValue" },
  132.     { TIFFTAG_MAXSAMPLEVALUE,    -1, TIFF_SHORT,    FIELD_MAXSAMPLEVALUE,
  133.       TRUE,    "MaxSampleValue" },
  134.     { TIFFTAG_XRESOLUTION,     1, TIFF_RATIONAL,FIELD_RESOLUTION,
  135.       TRUE,    "XResolution" },
  136.     { TIFFTAG_YRESOLUTION,     1, TIFF_RATIONAL,FIELD_RESOLUTION,
  137.       TRUE,    "YResolution" },
  138.     { TIFFTAG_PLANARCONFIG,     1, TIFF_SHORT,    FIELD_PLANARCONFIG,
  139.       FALSE,    "PlanarConfiguration" },
  140.     { TIFFTAG_PAGENAME,        -1, TIFF_ASCII,    FIELD_PAGENAME,
  141.       TRUE,    "PageName" },
  142.     { TIFFTAG_XPOSITION,     1, TIFF_RATIONAL,FIELD_POSITION,
  143.       TRUE,    "XPosition" },
  144.     { TIFFTAG_YPOSITION,     1, TIFF_RATIONAL,FIELD_POSITION,
  145.       TRUE,    "YPosition" },
  146.     { TIFFTAG_FREEOFFSETS,    -1, TIFF_LONG,    (u_short)-1,
  147.       FALSE,    "FreeOffsets" },
  148.     { TIFFTAG_FREEBYTECOUNTS,    -1, TIFF_LONG,    (u_short)-1,
  149.       FALSE,    "FreeByteCounts" },
  150.     { TIFFTAG_GRAYRESPONSEUNIT,     1, TIFF_SHORT,    FIELD_GRAYRESPONSEUNIT,
  151.       TRUE,    "GrayResponseUnit" },
  152.     { TIFFTAG_GRAYRESPONSECURVE,-1, TIFF_SHORT,    FIELD_GRAYRESPONSECURVE,
  153.       TRUE,    "GrayResponseCurve" },
  154.     { TIFFTAG_GROUP3OPTIONS,     1, TIFF_LONG,    FIELD_GROUP3OPTIONS,
  155.       FALSE,    "Group3Options" },
  156.     { TIFFTAG_GROUP4OPTIONS,     1, TIFF_LONG,    FIELD_GROUP4OPTIONS,
  157.       FALSE,    "Group4Options" },
  158.     { TIFFTAG_RESOLUTIONUNIT,     1, TIFF_SHORT,    FIELD_RESOLUTIONUNIT,
  159.       TRUE,    "ResolutionUnit" },
  160.     { TIFFTAG_PAGENUMBER,     2, TIFF_SHORT,    FIELD_PAGENUMBER,
  161.       TRUE,    "PageNumber" },
  162.     { TIFFTAG_COLORRESPONSEUNIT, 1, TIFF_SHORT,    FIELD_COLORRESPONSEUNIT,
  163.       TRUE,    "ColorResponseUnit" },
  164.     { TIFFTAG_COLORRESPONSECURVE,-1,TIFF_SHORT,    FIELD_COLORRESPONSECURVE,
  165.       TRUE,    "ColorResponseCurve" },
  166.     { TIFFTAG_SOFTWARE,        -1, TIFF_ASCII,    FIELD_SOFTWARE,
  167.       TRUE,    "Software" },
  168.     { TIFFTAG_DATETIME,        -1, TIFF_ASCII,    FIELD_DATETIME,
  169.       TRUE,    "DateTime" },
  170.     { TIFFTAG_ARTIST,        -1, TIFF_ASCII,    FIELD_ARTIST,
  171.       TRUE,    "Artist" },
  172.     { TIFFTAG_HOSTCOMPUTER,    -1, TIFF_ASCII,    FIELD_HOSTCOMPUTER,
  173.       TRUE,    "HostComputer" },
  174.     { TIFFTAG_PREDICTOR,     1, TIFF_SHORT,    FIELD_PREDICTOR,
  175.       FALSE,    "Predictor" },
  176.     { TIFFTAG_COLORMAP,         1, TIFF_SHORT,    FIELD_COLORMAP,
  177.       TRUE,    "ColorMap" },
  178.     { TIFFTAG_TILEWIDTH,     1, TIFF_LONG,    FIELD_TILEDIMENSIONS,
  179.       FALSE,    "TileWidth" },
  180.     { TIFFTAG_TILEWIDTH,     1, TIFF_SHORT,    FIELD_TILEDIMENSIONS,
  181.       FALSE,    "TileWidth" },
  182.     { TIFFTAG_TILELENGTH,     1, TIFF_LONG,    FIELD_TILEDIMENSIONS,
  183.       FALSE,    "TileLength" },
  184.     { TIFFTAG_TILELENGTH,     1, TIFF_SHORT,    FIELD_TILEDIMENSIONS,
  185.       FALSE,    "TileLength" },
  186.     { TIFFTAG_TILEOFFSETS,    1, TIFF_LONG,    FIELD_STRIPOFFSETS,
  187.       FALSE,    "TileOffsets" },
  188.     { TIFFTAG_TILEBYTECOUNTS,    1, TIFF_LONG,    FIELD_STRIPBYTECOUNTS,
  189.       FALSE,    "TileByteCounts" },
  190.     { TIFFTAG_TILEBYTECOUNTS,    1, TIFF_SHORT,    FIELD_STRIPBYTECOUNTS,
  191.       FALSE,    "TileByteCounts" },
  192.     { TIFFTAG_BADFAXLINES,     1, TIFF_LONG,    FIELD_BADFAXLINES,
  193.       TRUE,    "BadFaxLines" },
  194.     { TIFFTAG_BADFAXLINES,     1, TIFF_SHORT,    FIELD_BADFAXLINES,
  195.       TRUE,    "BadFaxLines" },
  196.     { TIFFTAG_CLEANFAXDATA,     1, TIFF_SHORT,    FIELD_CLEANFAXDATA,
  197.       TRUE,    "CleanFaxData" },
  198.     { TIFFTAG_CONSECUTIVEBADFAXLINES,1, TIFF_LONG,FIELD_BADFAXRUN,
  199.       TRUE,    "ConsecutiveBadFaxLines" },
  200.     { TIFFTAG_CONSECUTIVEBADFAXLINES,1, TIFF_SHORT,FIELD_BADFAXRUN,
  201.       TRUE,    "ConsecutiveBadFaxLines" },
  202.     { TIFFTAG_INKSET,        1, TIFF_SHORT,    FIELD_INKSET,
  203.       FALSE,    "InkSet" },
  204. /* begin SGI tags */
  205.     { TIFFTAG_MATTEING,        1, TIFF_SHORT,    FIELD_MATTEING,
  206.       FALSE,    "Matteing" },
  207.     { TIFFTAG_DATATYPE,        1, TIFF_SHORT,    FIELD_DATATYPE,
  208.       FALSE,    "DataType" },
  209.     { TIFFTAG_IMAGEDEPTH,    1, TIFF_LONG,    FIELD_IMAGEDEPTH,
  210.       FALSE,    "ImageDepth" },
  211.     { TIFFTAG_IMAGEDEPTH,    1, TIFF_SHORT,    FIELD_IMAGEDEPTH,
  212.       FALSE,    "ImageDepth" },
  213.     { TIFFTAG_TILEDEPTH,    1, TIFF_LONG,    FIELD_TILEDEPTH,
  214.       FALSE,    "TileDepth" },
  215.     { TIFFTAG_TILEDEPTH,    1, TIFF_SHORT,    FIELD_TILEDEPTH,
  216.       FALSE,    "TileDepth" },
  217. /* end SGI tags */
  218. #ifdef JPEG_SUPPORT        /* C-Cube JPEG tags */
  219.     { TIFFTAG_JPEGPROC,        1, TIFF_SHORT,    FIELD_JPEGPROC,
  220.       FALSE,    "JPEGProc" },
  221.     { TIFFTAG_JPEGQTABLEPREC,    1, TIFF_SHORT,    FIELD_JPEGQTABLEPREC,
  222.       FALSE,    "JPEGQTablePrecision" },
  223.     { TIFFTAG_JPEGQTABLES,    -1, TIFF_LONG,    FIELD_JPEGQTABLES,
  224.       FALSE,    "JPEGQTables" },
  225.     { TIFFTAG_JPEGDCTABLES,    -1, TIFF_LONG,    FIELD_JPEGDCTABLES,
  226.       FALSE,    "JPEGDCTables" },
  227.     { TIFFTAG_JPEGACTABLES,    -1, TIFF_LONG,    FIELD_JPEGACTABLES,
  228.       FALSE,    "JPEGACTables" },
  229. #endif
  230. };
  231. #define    NFIELDINFO    NITEMS(FieldInfo)
  232.  
  233. #define    IGNORE    0        /* tag placeholder used below */
  234.  
  235. static int datawidth[] = {
  236.     1,    /* nothing */
  237.     1,    /* TIFF_BYTE */
  238.     1,    /* TIFF_ASCII */
  239.     2,    /* TIFF_SHORT */
  240.     4,    /* TIFF_LONG */
  241.     8,    /* TIFF_RATIONAL */
  242. };
  243.  
  244. #include "prototypes.h"
  245. #if USE_PROTOTYPES
  246. static    EstimateStripByteCounts(TIFF *, TIFFDirEntry *, u_int);
  247. static    MissingRequired(TIFF *, char *);
  248. static    TIFFFetchData(TIFF *, TIFFDirEntry *, char *);
  249. static    TIFFFetchString(TIFF *, TIFFDirEntry *, char *);
  250. static    double TIFFFetchRational(TIFF *, TIFFDirEntry *);
  251. static    TIFFUnpackShorts(TIFF *, u_short [], TIFFDirEntry *);
  252. static    TIFFFetchPerSampleShorts(TIFF *, TIFFDirEntry *, long *);
  253. static    TIFFFetchStripThing(TIFF *, TIFFDirEntry *, long, u_long **);
  254. static    TIFFFetchJPEGQTables(TIFF *, TIFFDirEntry *);
  255. static    TIFFFetchJPEGCTables(TIFF *, TIFFDirEntry *, u_char ***);
  256. static    TIFFFieldInfo *FindFieldInfo(u_short, TIFFDataType);
  257. static    TIFFFieldInfo *FieldWithTag(u_short);
  258. static    TIFFGetField1(TIFFDirectory *, int, va_list);
  259. extern    int TIFFSetCompressionScheme(TIFF *, int);
  260. extern    int TIFFDefaultDirectory(TIFF*);
  261. extern    int TIFFFreeDirectory(TIFF*);
  262. #else
  263. static    EstimateStripByteCounts();
  264. static    MissingRequired();
  265. static    TIFFFetchData();
  266. static    TIFFFetchString();
  267. static    double TIFFFetchRational();
  268. static    TIFFUnpackShorts();
  269. static    TIFFFetchPerSampleShorts();
  270. static    TIFFFetchStripThing();
  271. static    TIFFFetchJPEGQTables();
  272. static    TIFFFetchJPEGCTables();
  273. static    TIFFFieldInfo *FindFieldInfo();
  274. static    TIFFFieldInfo *FieldWithTag();
  275. static    TIFFGetField1();
  276. extern    int TIFFSetCompressionScheme();
  277. extern    int TIFFDefaultDirectory();
  278. extern    int TIFFFreeDirectory();
  279. #endif
  280.  
  281. /*
  282.  * Read the next TIFF directory from a file
  283.  * and convert it to the internal format.
  284.  * We read directories sequentially.
  285.  */
  286. TIFFReadDirectory(tif)
  287.     TIFF *tif;
  288. {
  289.     register TIFFDirEntry *dp;
  290.     register int n;
  291.     register TIFFDirectory *td = NULL;
  292.     TIFFDirEntry *dir = NULL;
  293.     long v;
  294.     TIFFFieldInfo *fip;
  295.     u_short dircount;
  296.     char *cp;
  297.     int diroutoforderwarning = 0, ok;
  298.  
  299.     tif->tif_diroff = tif->tif_nextdiroff;
  300.     if (tif->tif_diroff == 0)        /* no more directories */
  301.         return (0);
  302.     if (!isMapped(tif)) {
  303.         if (!SeekOK(tif->tif_fd, tif->tif_diroff)) {
  304.             TIFFError(tif->tif_name,
  305.                 "Seek error accessing TIFF directory");
  306.             return (0);
  307.         }
  308.         if (!ReadOK(tif->tif_fd, &dircount, sizeof (short))) {
  309.             TIFFError(tif->tif_name,
  310.                 "Can not read TIFF directory count");
  311.             return (0);
  312.         }
  313.         if (tif->tif_flags & TIFF_SWAB)
  314.             TIFFSwabShort(&dircount);
  315.         dir = (TIFFDirEntry *)malloc(dircount * sizeof (TIFFDirEntry));
  316.         if (dir == NULL) {
  317.             TIFFError(tif->tif_name,
  318.                 "No space to read TIFF directory");
  319.             return (0);
  320.         }
  321.         if (!ReadOK(tif->tif_fd, dir, dircount*sizeof (TIFFDirEntry))) {
  322.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  323.             goto bad;
  324.         }
  325.         /*
  326.          * Read offset to next directory for sequential scans.
  327.          */
  328.         if (!ReadOK(tif->tif_fd, &tif->tif_nextdiroff, sizeof (long)))
  329.             tif->tif_nextdiroff = 0;
  330. #ifdef MMAP_SUPPORT
  331.     } else {
  332.         off_t off = tif->tif_diroff;
  333.  
  334.         if (off + sizeof (short) > tif->tif_size) {
  335.             TIFFError(tif->tif_name,
  336.                 "Can not read TIFF directory count");
  337.             return (0);
  338.         } else
  339.             bcopy(tif->tif_base + off, &dircount, sizeof (short));
  340.         off += sizeof (short);
  341.         if (tif->tif_flags & TIFF_SWAB)
  342.             TIFFSwabShort(&dircount);
  343.         dir = (TIFFDirEntry *)malloc(dircount * sizeof (TIFFDirEntry));
  344.         if (dir == NULL) {
  345.             TIFFError(tif->tif_name,
  346.                 "No space to read TIFF directory");
  347.             return (0);
  348.         }
  349.         if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) {
  350.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  351.             goto bad;
  352.         } else
  353.             bcopy(tif->tif_base + off, dir,
  354.                 dircount*sizeof (TIFFDirEntry));
  355.         off += dircount* sizeof (TIFFDirEntry);
  356.         if (off + sizeof (long) < tif->tif_size)
  357.             bcopy(tif->tif_base + off, &tif->tif_nextdiroff,
  358.                 sizeof (long));
  359.         else
  360.             tif->tif_nextdiroff = 0;
  361. #endif
  362.     }
  363.     if (tif->tif_flags & TIFF_SWAB)
  364.         TIFFSwabLong((u_long *)&tif->tif_nextdiroff);
  365.  
  366.     tif->tif_flags &= ~TIFF_BEENWRITING;    /* reset before new dir */
  367.     /*
  368.      * Setup default value and then make a pass over
  369.      * the fields to check type and tag information,
  370.      * and to extract info required to size data
  371.      * structures.  A second pass is made afterwards
  372.      * to read in everthing not taken in the first pass.
  373.      */
  374.     td = &tif->tif_dir;
  375.     if (tif->tif_diroff != tif->tif_header.tiff_diroff) {
  376.         /* free any old stuff and reinit */
  377.         TIFFFreeDirectory(tif);
  378.     }
  379.     TIFFDefaultDirectory(tif);
  380.     /*
  381.      * Electronic Arts writes gray-scale TIFF files
  382.      * without a PlanarConfiguration directory entry.
  383.      * Thus we setup a default value here, even though
  384.      * the TIFF spec says there is no default value.
  385.      */
  386.     TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  387.     for (fip = FieldInfo, dp = dir, n = dircount; n > 0; n--, dp++) {
  388.         if (tif->tif_flags & TIFF_SWAB) {
  389.             TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
  390.             TIFFSwabArrayOfLong(&dp->tdir_count, 2);
  391.         }
  392.         /*
  393.          * Find the field information entry for this tag.
  394.          */
  395.         /*
  396.          * Silicon Beach (at least) writes unordered
  397.          * directory tags (violating the spec).  Handle
  398.          * it here, but be obnoxious (maybe they'll
  399.          * fix it?).
  400.          */
  401.         if (dp->tdir_tag < fip->field_tag) {
  402.             if (!diroutoforderwarning) {
  403.                 TIFFWarning(tif->tif_name,
  404.     "Invalid TIFF directory; tags are not sorted in ascending order");
  405.                 diroutoforderwarning = 1;
  406.             }
  407.             fip = FieldInfo;    /* O(n^2) */
  408.         }
  409.         while (fip < &FieldInfo[NFIELDINFO] &&
  410.             fip->field_tag < dp->tdir_tag)
  411.             fip++;
  412.         if (fip >= &FieldInfo[NFIELDINFO] ||
  413.             fip->field_tag != dp->tdir_tag) {
  414.             TIFFWarning(tif->tif_name,
  415.                 "ignoring unknown field with tag %d (0x%x)",
  416.                 dp->tdir_tag,  dp->tdir_tag);
  417.             dp->tdir_tag = IGNORE;
  418.             fip = FieldInfo;    /* restart search */
  419.             continue;
  420.         }
  421.         /*
  422.          * Null out old tags that we ignore.
  423.          */
  424.         if (fip->field_bit == (u_short)-1) {
  425.             dp->tdir_tag = IGNORE;
  426.             continue;
  427.         }
  428.         /*
  429.          * Check data type.
  430.          */
  431.         while (dp->tdir_type != (u_short)fip->field_type) {
  432.             fip++;
  433.             if (fip >= &FieldInfo[NFIELDINFO] ||
  434.                 fip->field_tag != dp->tdir_tag) {
  435.                 TIFFError(tif->tif_name,
  436.                     "Wrong data type %d for field \"%s\"",
  437.                     dp->tdir_type, fip[-1].field_name);
  438.                 goto bad;
  439.             }
  440.         }
  441.         switch (dp->tdir_tag) {
  442.         case TIFFTAG_STRIPOFFSETS:
  443.         case TIFFTAG_STRIPBYTECOUNTS:
  444.         case TIFFTAG_TILEOFFSETS:
  445.         case TIFFTAG_TILEBYTECOUNTS:
  446.             TIFFSetFieldBit(tif, fip->field_bit);
  447.             break;
  448.         case TIFFTAG_IMAGEWIDTH:
  449.         case TIFFTAG_IMAGELENGTH:
  450.         case TIFFTAG_IMAGEDEPTH:
  451.         case TIFFTAG_TILELENGTH:
  452.         case TIFFTAG_TILEWIDTH:
  453.         case TIFFTAG_TILEDEPTH:
  454.         case TIFFTAG_PLANARCONFIG:
  455.         case TIFFTAG_SAMPLESPERPIXEL:
  456.             if (!TIFFSetField(tif, dp->tdir_tag, (int)
  457.               TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  458.                 goto bad;
  459.             break;
  460.         case TIFFTAG_ROWSPERSTRIP:
  461.             if (!TIFFSetField(tif, dp->tdir_tag, (long)
  462.               TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  463.                 goto bad;
  464.             break;
  465.         }
  466.     }
  467.  
  468.     /*
  469.      * Allocate directory structure and setup defaults.
  470.      */
  471.     if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
  472.         MissingRequired(tif, "ImageLength");
  473.         goto bad;
  474.     }
  475.     if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
  476.         MissingRequired(tif, "PlanarConfiguration");
  477.         goto bad;
  478.     }
  479.     /* 
  480.       * Setup appropriate structures (by strip or by tile)
  481.      */
  482.     if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
  483.         td->td_stripsperimage = (td->td_rowsperstrip == 0xffffffff ?
  484.              (td->td_imagelength != 0 ? 1 : 0) :
  485.              howmany(td->td_imagelength, td->td_rowsperstrip));
  486.         td->td_tilewidth = td->td_imagewidth;
  487.         td->td_tilelength = td->td_rowsperstrip;
  488.         td->td_tiledepth = td->td_imagedepth;
  489.         tif->tif_flags &= ~TIFF_ISTILED;
  490.     } else {
  491.         td->td_stripsperimage = TIFFNumberOfTiles(tif);
  492.         tif->tif_flags |= TIFF_ISTILED;
  493.     }
  494.     td->td_nstrips = td->td_stripsperimage;
  495.     if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
  496.         td->td_nstrips *= td->td_samplesperpixel;
  497.     if (td->td_nstrips > 0 && !TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
  498.         MissingRequired(tif,
  499.             isTiled(tif) ? "TileOffsets" : "StripOffsets");
  500.         goto bad;
  501.     }
  502.  
  503.     /*
  504.      * Second pass: extract other information.
  505.      *
  506.      * Should do a better job of verifying values.
  507.      */
  508.     for (dp = dir, n = dircount; n > 0; n--, dp++) {
  509.         if (dp->tdir_tag == IGNORE)
  510.             continue;
  511.         switch (dp->tdir_tag) {
  512.         case TIFFTAG_COMPRESSION:
  513.             /*
  514.              * The 5.0 spec says the compression tag has
  515.              * one value, while earlier specs say it has
  516.              * one value per sample.  Because of this, we
  517.              * accept the tag if one value is supplied.
  518.              */
  519.             if (dp->tdir_count == 1) {
  520.                 v = TIFFExtractData(tif,
  521.                     dp->tdir_type, dp->tdir_offset);
  522.                 if (!TIFFSetField(tif,
  523.                      TIFFTAG_COMPRESSION, (int)v))
  524.                     goto bad;
  525.                 break;
  526.             }
  527.             /* fall thru... */
  528.         case TIFFTAG_MINSAMPLEVALUE:
  529.         case TIFFTAG_MAXSAMPLEVALUE:
  530.         case TIFFTAG_BITSPERSAMPLE:
  531.         case TIFFTAG_DATATYPE:
  532.             if (!TIFFFetchPerSampleShorts(tif, dp, &v) ||
  533.                 !TIFFSetField(tif, dp->tdir_tag, (int)v))
  534.                 goto bad;
  535.             break;
  536.         case TIFFTAG_STRIPOFFSETS:
  537.         case TIFFTAG_TILEOFFSETS:
  538.             if (!TIFFFetchStripThing(tif, dp,
  539.                 td->td_nstrips, &td->td_stripoffset))
  540.                 goto bad;
  541.             TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
  542.             break;
  543.         case TIFFTAG_STRIPBYTECOUNTS:
  544.         case TIFFTAG_TILEBYTECOUNTS:
  545.             if (!TIFFFetchStripThing(tif, dp,
  546.                 td->td_nstrips, &td->td_stripbytecount))
  547.                 goto bad;
  548.             TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  549.             break;
  550.         case TIFFTAG_IMAGELENGTH:
  551.         case TIFFTAG_ROWSPERSTRIP:
  552.         case TIFFTAG_TILELENGTH:
  553.         case TIFFTAG_TILEWIDTH:
  554.         case TIFFTAG_TILEDEPTH:
  555.         case TIFFTAG_SAMPLESPERPIXEL:
  556.         case TIFFTAG_PLANARCONFIG:
  557.             /* handled in first pass above */
  558.             break;
  559.         case TIFFTAG_GRAYRESPONSECURVE:
  560.         case TIFFTAG_COLORRESPONSECURVE:
  561.         case TIFFTAG_COLORMAP:
  562.             v = (1L<<td->td_bitspersample) * sizeof (u_short);
  563.             cp = malloc(dp->tdir_tag == TIFFTAG_GRAYRESPONSECURVE ? 
  564.                 v : 3*v);
  565.             if (cp == NULL)
  566.                 goto bad;
  567.             ok = (TIFFFetchData(tif, dp, cp) &&
  568.                 TIFFSetField(tif, dp->tdir_tag, cp,cp+v,cp+2*v));
  569.             free(cp);
  570.             if (!ok)
  571.                 goto bad;
  572.             break;
  573.         case TIFFTAG_PAGENUMBER:
  574.             TIFFUnpackShorts(tif, td->td_pagenumber, dp);
  575.             TIFFSetFieldBit(tif, FIELD_PAGENUMBER);
  576.             break;
  577. #ifdef JPEG_SUPPORT
  578.         case TIFFTAG_JPEGQTABLES:
  579.             if (!TIFFFetchJPEGQTables(tif, dp))
  580.                 goto bad;
  581.             TIFFSetFieldBit(tif, FIELD_JPEGQTABLES);
  582.             break;
  583.         case TIFFTAG_JPEGDCTABLES:
  584.             if (!TIFFFetchJPEGCTables(tif, dp, &td->td_dctab))
  585.                 goto bad;
  586.             TIFFSetFieldBit(tif, FIELD_JPEGDCTABLES);
  587.             break;
  588.         case TIFFTAG_JPEGACTABLES:
  589.             if (!TIFFFetchJPEGCTables(tif, dp, &td->td_actab))
  590.                 goto bad;
  591.             TIFFSetFieldBit(tif, FIELD_JPEGACTABLES);
  592.             break;
  593. #endif
  594. /* BEGIN REV 4.0 COMPATIBILITY */
  595.         case TIFFTAG_OSUBFILETYPE:
  596.             v = 0;
  597.             switch (TIFFExtractData(tif, dp->tdir_type,
  598.                 dp->tdir_offset)) {
  599.             case OFILETYPE_REDUCEDIMAGE:
  600.                 v = FILETYPE_REDUCEDIMAGE;
  601.                 break;
  602.             case OFILETYPE_PAGE:
  603.                 v = FILETYPE_PAGE;
  604.                 break;
  605.             }
  606.             if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
  607.                 goto bad;
  608.             break;
  609. /* END REV 4.0 COMPATIBILITY */
  610.         default:
  611.             switch (dp->tdir_type) {
  612.             case TIFF_BYTE:
  613.             case TIFF_SHORT:
  614.             case TIFF_LONG:
  615.                 if (!TIFFSetField(tif, dp->tdir_tag, (int)
  616.               TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  617.                     goto bad;
  618.                 break;
  619.             case TIFF_RATIONAL:
  620.                 if (!TIFFSetField(tif, dp->tdir_tag,
  621.                     TIFFFetchRational(tif, dp)))
  622.                     goto bad;
  623.                 break;
  624.             case TIFF_ASCII:
  625.                 if (dp->tdir_count > 0) {
  626.                     cp = malloc(dp->tdir_count);
  627.                     if (cp == NULL)
  628.                         goto bad;
  629.                     ok = (TIFFFetchString(tif, dp, cp) &&
  630.                        TIFFSetField(tif, dp->tdir_tag, cp));
  631.                     free(cp);
  632.                     if (!ok)
  633.                         goto bad;
  634.                 }
  635.                 break;
  636.             }
  637.             break;
  638.         }
  639.     }
  640.     if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
  641.         /*
  642.          * Some manufacturers violate the spec by not giving
  643.          * the size of the strips.  In this case, assume there
  644.          * is one uncompressed strip of data.
  645.          */
  646.         if (td->td_nstrips > 1) {
  647.             MissingRequired(tif, "StripByteCounts");
  648.             goto bad;
  649.         }
  650.         TIFFWarning(tif->tif_name,
  651. "TIFF directory is missing required \"%s\" field, calculating from imagelength",
  652.             FieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
  653.         EstimateStripByteCounts(tif, dir, dircount);
  654.     } else if (td->td_nstrips == 1 && td->td_stripbytecount[0] == 0) {
  655.         /*
  656.          * Plexus (and others) sometimes give a value
  657.          * of zero for a tag when they don't know what
  658.          * the correct value is!  Try and handle the
  659.          * simple case of estimating the size of a one
  660.          * strip image.
  661.          */
  662.         TIFFWarning(tif->tif_name,
  663. "Bogus \"%s\" field, ignoring and calculating from imagelength",
  664.             FieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
  665.         EstimateStripByteCounts(tif, dir, dircount);
  666.     }
  667.     if (dir)
  668.         free((char *)dir);
  669.     if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
  670.         td->td_maxsamplevalue = (1L<<td->td_bitspersample)-1;
  671.     /*
  672.      * Setup default compression scheme.
  673.      */
  674.     if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
  675.         TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  676.     /*
  677.      * Reinitialize i/o since we are starting on a new directory.
  678.      */
  679.     tif->tif_row = -1;
  680.     tif->tif_curstrip = -1;
  681.     tif->tif_col = -1;
  682.     tif->tif_curtile = -1;
  683.     tif->tif_tilesize = TIFFTileSize(tif);
  684.     tif->tif_scanlinesize = TIFFScanlineSize(tif);
  685.     return (1);
  686. bad:
  687.     if (dir)
  688.         free((char *)dir);
  689.     return (0);
  690. }
  691.  
  692. static
  693. EstimateStripByteCounts(tif, dir, dircount)
  694.     TIFF *tif;
  695.     TIFFDirEntry *dir;
  696.     u_int dircount;
  697. {
  698.     register TIFFDirEntry *dp;
  699.     register TIFFDirectory *td = &tif->tif_dir;
  700.     register int n;
  701.  
  702.     td->td_stripbytecount = (u_long *)malloc(sizeof (u_long));
  703.     if (td->td_compression != COMPRESSION_NONE) {
  704.         u_long space = sizeof (TIFFHeader)
  705.             + sizeof (short)
  706.             + (dircount * sizeof (TIFFDirEntry))
  707.             + sizeof (long);
  708.         /* calculate amount of space used by indirect values */
  709.         for (dp = dir, n = dircount; n > 0; n--, dp++) {
  710.             int cc = dp->tdir_count * datawidth[dp->tdir_type];
  711.             if (cc > sizeof (long))
  712.                 space += cc;
  713.         }
  714.         td->td_stripbytecount[0] = TIFFGetFileSize(tif->tif_fd) - space;
  715.     } else {
  716.         u_long rowbytes = howmany(td->td_bitspersample *
  717.             td->td_samplesperpixel * td->td_imagewidth, 8);
  718.         td->td_stripbytecount[0] = td->td_imagelength * rowbytes;
  719.     }
  720.     TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  721.     if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
  722.         td->td_rowsperstrip = td->td_imagelength;
  723. }
  724.  
  725. static
  726. MissingRequired(tif, tagname)
  727.     TIFF *tif;
  728.     char *tagname;
  729. {
  730.     TIFFError(tif->tif_name,
  731.         "TIFF directory is missing required \"%s\" field", tagname);
  732. }
  733.  
  734. /*
  735.  * Fetch a contiguous directory item.
  736.  */
  737. static
  738. TIFFFetchData(tif, dir, cp)
  739.     TIFF *tif;
  740.     TIFFDirEntry *dir;
  741.     char *cp;
  742. {
  743.     int cc, w;
  744.  
  745.     w = datawidth[dir->tdir_type];
  746.     cc = dir->tdir_count * w;
  747.     if (!isMapped(tif)) {
  748.         if (!SeekOK(tif->tif_fd, dir->tdir_offset))
  749.             goto bad;
  750.         if (!ReadOK(tif->tif_fd, cp, cc))
  751.             goto bad;
  752. #ifdef MMAP_SUPPORT
  753.     } else {
  754.         if (dir->tdir_offset + cc > tif->tif_size)
  755.             goto bad;
  756.         bcopy(tif->tif_base + dir->tdir_offset, cp, cc);
  757. #endif
  758.     }
  759.     if (tif->tif_flags & TIFF_SWAB) {
  760.         switch (dir->tdir_type) {
  761.         case TIFF_SHORT:
  762.             TIFFSwabArrayOfShort((u_short *)cp, dir->tdir_count);
  763.             break;
  764.         case TIFF_LONG:
  765.             TIFFSwabArrayOfLong((u_long *)cp, dir->tdir_count);
  766.             break;
  767.         case TIFF_RATIONAL:
  768.             TIFFSwabArrayOfLong((u_long *)cp, 2*dir->tdir_count);
  769.             break;
  770.         }
  771.     }
  772.     return (cc);
  773. bad:
  774.     TIFFError(tif->tif_name, "Error fetching data for field \"%s\"",
  775.         FieldWithTag(dir->tdir_tag)->field_name);
  776.     return (0);
  777. }
  778.  
  779. /*
  780.  * Fetch an ASCII item from the file.
  781.  */
  782. static
  783. TIFFFetchString(tif, dir, cp)
  784.     TIFF *tif;
  785.     TIFFDirEntry *dir;
  786.     char *cp;
  787. {
  788.     if (dir->tdir_count <= 4) {
  789.         u_long l = dir->tdir_offset;
  790.         if (tif->tif_flags & TIFF_SWAB)
  791.             TIFFSwabLong(&l);
  792.         bcopy(&l, cp, dir->tdir_count);
  793.         return (1);
  794.     }
  795.     return (TIFFFetchData(tif, dir, cp));
  796. }
  797.  
  798. /*
  799.  * Fetch a rational item from the file
  800.  * at offset off.  We return the value
  801.  * as floating point number.
  802.  */
  803. static double
  804. TIFFFetchRational(tif, dir)
  805.     TIFF *tif;
  806.     TIFFDirEntry *dir;
  807. {
  808.     long l[2];
  809.  
  810.     if (!TIFFFetchData(tif, dir, (char *)l))
  811.         return (1.);
  812.     if (l[1] == 0) {
  813.         TIFFError(tif->tif_name, "%s: Rational with zero denominator",
  814.             FieldWithTag(dir->tdir_tag)->field_name);
  815.         return (1.);
  816.     }
  817.     return ((double)l[0] / (double)l[1]);
  818. }
  819.  
  820. /*
  821.  * Unpack a pair of short values from the
  822.  * offset field of a directory entry.
  823.  */
  824. static
  825. TIFFUnpackShorts(tif, v, dir)
  826.     TIFF *tif;
  827.     u_short v[];
  828.     TIFFDirEntry *dir;
  829. {
  830.     if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  831.         v[0] = dir->tdir_offset >> 16;
  832.         v[1] = dir->tdir_offset & 0xffff;
  833.     } else {
  834.         v[0] = dir->tdir_offset & 0xffff;
  835.         v[1] = dir->tdir_offset >> 16;
  836.     }
  837. }
  838.  
  839. /*
  840.  * Check the count field of a directory
  841.  * entry against the samples/pixel.
  842.  */
  843. static
  844. CheckSampleCount(tif, dir)
  845.     TIFF *tif;
  846.     TIFFDirEntry *dir;
  847. {
  848.     if (tif->tif_dir.td_samplesperpixel != dir->tdir_count) {
  849.         TIFFError(tif->tif_name, "Incorrect count %d for field \"%s\"",
  850.             dir->tdir_count, FieldWithTag(dir->tdir_tag)->field_name);
  851.         return (0);
  852.     }
  853.     return (1);
  854. }
  855.  
  856. /*
  857.  * Fetch samples/pixel short values for 
  858.  * the specified tag and verify that
  859.  * all values are the same.
  860.  */
  861. static
  862. TIFFFetchPerSampleShorts(tif, dir, pl)
  863.     TIFF *tif;
  864.     TIFFDirEntry *dir;
  865.     long *pl;
  866. {
  867.     u_short v[4];
  868.     int i;
  869.  
  870.     if (!CheckSampleCount(tif, dir))
  871.         return (0);
  872.     switch (dir->tdir_count) {
  873.     case 1:
  874.         *pl = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
  875.         return (1);
  876.     case 2:
  877.         TIFFUnpackShorts(tif, v, dir);
  878.         break;
  879.     default:
  880.         if (!TIFFFetchData(tif, dir, (char *)v))
  881.             return (0);
  882.         break;
  883.     }
  884.     for (i = 1; i < dir->tdir_count; i++)
  885.         if (v[i] != v[0]) {
  886.             TIFFError(tif->tif_name,
  887.     "Cannot handle different per-sample values for field \"%s\"",
  888.                  FieldWithTag(dir->tdir_tag)->field_name);
  889.             return (0);
  890.         }
  891.     *pl = v[0];
  892.     return (1);
  893. }
  894.  
  895. /*
  896.  * Fetch a set of offsets or lengths.
  897.  * While this routine says "strips",
  898.  * in fact it's also used for tiles.
  899.  */
  900. static
  901. TIFFFetchStripThing(tif, dir, nstrips, lpp)
  902.     TIFF *tif;
  903.     TIFFDirEntry *dir;
  904.     long nstrips;
  905.     u_long **lpp;
  906. {
  907.     register u_long *lp;
  908.     int status;
  909.  
  910.     if (nstrips != dir->tdir_count) {
  911.         TIFFError(tif->tif_name,
  912.             "Count mismatch for field \"%s\"; expecting %d, got %d",
  913.             FieldWithTag(dir->tdir_tag)->field_name, nstrips,
  914.             dir->tdir_count);
  915.         return (0);
  916.     }
  917.     /*
  918.      * Allocate space for strip information.
  919.      */
  920.     if (*lpp == NULL &&
  921.         (*lpp = (u_long *)malloc(nstrips * sizeof (u_long))) == NULL) {
  922.         TIFFError(tif->tif_name, "No space for \"%s\" array",
  923.             FieldWithTag(dir->tdir_tag)->field_name);
  924.         return (0);
  925.     }
  926.     lp = *lpp;
  927.     status = 1;
  928.     if (dir->tdir_type == (int)TIFF_SHORT) {
  929.         /*
  930.          * Handle short->long expansion.
  931.          */
  932.         if (dir->tdir_count > 2) {
  933.             char *dp =
  934.                 malloc(dir->tdir_count*datawidth[(int)TIFF_SHORT]);
  935.             if (dp == NULL) {
  936.                 TIFFError(tif->tif_name,
  937.                     "No memory to fetch field \"%s\"",
  938.                     FieldWithTag(dir->tdir_tag)->field_name);
  939.                 return (0);
  940.             }
  941.             if (status = TIFFFetchData(tif, dir, dp)) {
  942.                 register u_short *wp = (u_short *)dp;
  943.                 while (nstrips-- > 0)
  944.                     *lp++ = *wp++;
  945.             }
  946.             free(dp);
  947.         } else {
  948.             /*
  949.              * Extract data from offset field.
  950.              */
  951.             if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  952.                 *lp++ = dir->tdir_offset >> 16;
  953.                 if (dir->tdir_count > 1)
  954.                     *lp = dir->tdir_offset & 0xffff;
  955.             } else {
  956.                 *lp++ = dir->tdir_offset & 0xffff;
  957.                 if (dir->tdir_count > 1)
  958.                     *lp = dir->tdir_offset >> 16;
  959.             }
  960.         }
  961.     } else {
  962.         if (dir->tdir_count > 1)
  963.             status = TIFFFetchData(tif, dir, (char *)lp);
  964.         else
  965.             *lp = dir->tdir_offset;
  966.     }
  967.     return (status);
  968. }
  969.  
  970. #ifdef JPEG_SUPPORT
  971. /*
  972.  * Fetch the JPEG Quantization tables
  973.  * for the specified directory entry.
  974.  * Storage for the td_qtab array is
  975.  * allocated as a side effect.
  976.  */
  977. static
  978. TIFFFetchJPEGQTables(tif, dir)
  979.     TIFF *tif;
  980.     TIFFDirEntry *dir;
  981. {
  982.     TIFFDirectory *td = &tif->tif_dir;
  983.     long off[4];
  984.     int i, j;
  985.     TIFFDirEntry tdir;
  986.     char *qmat;
  987.  
  988.     if (!CheckSampleCount(tif, dir))
  989.         return (0);
  990.     if (!TIFFFieldSet(tif, FIELD_JPEGQTABLEPREC)) {
  991.         TIFFError(tif->tif_name, "Missing JPEG Q table precision");
  992.         return (0);
  993.     }
  994.     if (dir->tdir_count > 1) {
  995.         /* XXX verify count <= 4 */
  996.         if (!TIFFFetchData(tif, dir, (char *)off))
  997.             return (0);
  998.     } else
  999.         off[0] = dir->tdir_offset;
  1000.     /*
  1001.      * We don't share per-component q matrices because
  1002.      * (besides complicating this logic even more), it
  1003.      * would make it very painful if the user does a ``set''.
  1004.      */
  1005.     td->td_qtab = (u_short **)
  1006.         malloc(dir->tdir_count*(sizeof (u_short *) + 64*sizeof (u_short)));
  1007.     tdir.tdir_type =
  1008.        (td->td_jpegprec == JPEGQTABLEPREC_8BIT ? TIFF_BYTE : TIFF_SHORT);
  1009.     tdir.tdir_count = 64;
  1010.     qmat = (((char *)td->td_qtab) + dir->tdir_count*sizeof (u_short *));
  1011.     for (i = 0; i < dir->tdir_count; i++) {
  1012.         td->td_qtab[i] = (u_short *)qmat;
  1013.         tdir.tdir_offset = off[i];
  1014.         if (tdir.tdir_type == TIFF_BYTE) {
  1015.             /*
  1016.              * Read Q matrix into the upper half of the
  1017.              * short-sized array and then expand from
  1018.              * 8-bit values to 16-bit values.
  1019.              */
  1020.             if (!TIFFFetchData(tif, &tdir, qmat+64))
  1021.                 return (0);
  1022.             for (j = 0; j < 64; j++)
  1023.                 td->td_qtab[i][j] = qmat[64+j];
  1024.         } else {
  1025.             if (!TIFFFetchData(tif, &tdir, qmat))
  1026.                 return (0);
  1027.         }
  1028.         qmat += 64*sizeof (u_short);
  1029.     }
  1030.     return (1);
  1031. }
  1032.  
  1033. /*
  1034.  * Fetch JPEG Huffman code tables for the
  1035.  * specified directory entry.  Storage for
  1036.  * the tables are allocated as a side effect.
  1037.  */
  1038. static
  1039. TIFFFetchJPEGCTables(tif, dir, ptab)
  1040.     TIFF *tif;
  1041.     TIFFDirEntry *dir;
  1042.     u_char ***ptab;
  1043. {
  1044.     TIFFDirectory *td = &tif->tif_dir;
  1045.     long off[4];
  1046.     int i, j, ncodes;
  1047.     TIFFDirEntry tdir;
  1048.     char *tab;
  1049.  
  1050.     if (!CheckSampleCount(tif, dir))
  1051.         return (0);
  1052.     if (dir->tdir_count > 1) {
  1053.         /* XXX verify count <= 4 */
  1054.         if (!TIFFFetchData(tif, dir, (char *)off))
  1055.             return (0);
  1056.     } else
  1057.         off[0] = dir->tdir_offset;
  1058.     /*
  1059.      * We don't share per-component tables because
  1060.      * (besides complicating this logic even more), it
  1061.      * would make it very painful if the user does a
  1062.      * ``set''.  Note also that we don't try to optimize
  1063.      * storage of the tables -- we just allocate enough
  1064.      * space to hold the largest possible.  All this
  1065.      * stuff is so complicated 'cuz the tag is defined
  1066.      * to be compatible with the JPEG table format,
  1067.      * rather than something that fits well into the
  1068.      * structure of TIFF -- argh!
  1069.      */
  1070.     *ptab = (u_char **)malloc(dir->tdir_count*
  1071.         (sizeof (u_char *) + (16+256)*sizeof (u_char)));
  1072.     tdir.tdir_type = TIFF_BYTE;
  1073.     tab = (((char *)*ptab) + dir->tdir_count*sizeof (u_char *));
  1074.     for (i = 0; i < dir->tdir_count; i++) {
  1075.         (*ptab)[i] = (u_char *)tab;
  1076.         tdir.tdir_offset = off[i];
  1077.         tdir.tdir_count = 16;
  1078.         /*
  1079.          * We must fetch the array that holds the
  1080.          * count of codes for each bit length first
  1081.          * and the count up the number of codes that
  1082.          * are in the variable length table.  This
  1083.          * information is implicit in the JPEG format
  1084.          * 'cuz it's preceded by a length field.
  1085.          */
  1086.         if (!TIFFFetchData(tif, &tdir, tab))    /* count array */
  1087.             return (0);
  1088.         for (ncodes = 0, j = 0; j < 16; j++)
  1089.             ncodes += tab[j];
  1090.         /*
  1091.          * Adjust offsets and fetch codes separately.
  1092.          */
  1093.         tdir.tdir_offset += 16;
  1094.         tdir.tdir_count = ncodes;
  1095.         tab += 16;
  1096.         if (!TIFFFetchData(tif, &tdir, tab))
  1097.             return (0);
  1098.         tab += ncodes;
  1099.     }
  1100.     return (1);
  1101. }
  1102. #endif
  1103.  
  1104. static TIFFFieldInfo *
  1105. DECLARE2(FindFieldInfo, u_short, tag, TIFFDataType, dt)
  1106. {
  1107.     register TIFFFieldInfo *fip;
  1108.  
  1109.     /* NB: if table gets big, use sorted search (e.g. binary search) */
  1110.     for (fip = FieldInfo; fip < &FieldInfo[NFIELDINFO]; fip++)
  1111.         if (fip->field_tag == tag &&
  1112.             (dt == TIFF_ANY || fip->field_type == dt))
  1113.             return (fip);
  1114.     return ((TIFFFieldInfo *)0);
  1115. }
  1116.  
  1117. static TIFFFieldInfo *
  1118. DECLARE1(FieldWithTag, u_short, tag)
  1119. {
  1120.     TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1121.     if (fip)
  1122.         return (fip);
  1123.     TIFFError("FieldWithTag", "Internal error, unknown tag 0x%x", tag);
  1124.     exit(-1);
  1125.     /*NOTREACHED*/
  1126. }
  1127.  
  1128. #define    CleanupField(field, member) {        \
  1129.     if (TIFFFieldSet(tif, field)) {        \
  1130.     free((char *)td->member);        \
  1131.     td->member = 0;                \
  1132.     }                        \
  1133. }
  1134. TIFFFreeDirectory(tif)
  1135.     TIFF *tif;
  1136. {
  1137.     register TIFFDirectory *td = &tif->tif_dir;
  1138.  
  1139.     CleanupField(FIELD_GRAYRESPONSECURVE, td_grayresponsecurve);
  1140.     if (TIFFFieldSet(tif, FIELD_COLORRESPONSECURVE)) {
  1141.         free(td->td_redresponsecurve), td->td_redresponsecurve = 0;
  1142.         free(td->td_greenresponsecurve), td->td_greenresponsecurve = 0;
  1143.         free(td->td_blueresponsecurve), td->td_blueresponsecurve = 0;
  1144.     }
  1145.     if (TIFFFieldSet(tif, FIELD_COLORMAP)) {
  1146.         free(td->td_redcolormap), td->td_redcolormap = 0;
  1147.         free(td->td_greencolormap), td->td_greencolormap = 0;
  1148.         free(td->td_bluecolormap), td->td_bluecolormap = 0;
  1149.     }
  1150.     CleanupField(FIELD_DOCUMENTNAME, td_documentname);
  1151.     CleanupField(FIELD_ARTIST, td_artist);
  1152.     CleanupField(FIELD_DATETIME, td_datetime);
  1153.     CleanupField(FIELD_HOSTCOMPUTER, td_hostcomputer);
  1154.     CleanupField(FIELD_IMAGEDESCRIPTION, td_imagedescription);
  1155.     CleanupField(FIELD_MAKE, td_make);
  1156.     CleanupField(FIELD_MODEL, td_model);
  1157.     CleanupField(FIELD_SOFTWARE, td_software);
  1158.     CleanupField(FIELD_PAGENAME, td_pagename);
  1159. #ifdef JPEG_SUPPORT
  1160.     CleanupField(FIELD_JPEGQTABLES, td_qtab);
  1161.     CleanupField(FIELD_JPEGDCTABLES, td_dctab);
  1162.     CleanupField(FIELD_JPEGACTABLES, td_actab);
  1163. #endif
  1164.     if  (td->td_stripoffset) {
  1165.         free((char *)td->td_stripoffset);
  1166.         td->td_stripoffset = NULL;
  1167.     }
  1168.     if  (td->td_stripbytecount) {
  1169.         free((char *)td->td_stripbytecount);
  1170.         td->td_stripbytecount = NULL;
  1171.     }
  1172. }
  1173. #undef CleanupField
  1174.  
  1175. /*
  1176.  * Setup a default directory structure.
  1177.  */
  1178. TIFFDefaultDirectory(tif)
  1179.     TIFF *tif;
  1180. {
  1181.     register TIFFDirectory *td = &tif->tif_dir;
  1182.  
  1183.     bzero((char *)td, sizeof (*td));
  1184.     td->td_fillorder = FILLORDER_MSB2LSB;
  1185.     td->td_bitspersample = 1;
  1186.     td->td_threshholding = THRESHHOLD_BILEVEL;
  1187.     td->td_orientation = ORIENTATION_TOPLEFT;
  1188.     td->td_samplesperpixel = 1;
  1189.     td->td_predictor = 1;
  1190.     td->td_rowsperstrip = 0xffffffff;
  1191.     td->td_tilewidth = 0xffffffff;
  1192.     td->td_tilelength = 0xffffffff;
  1193.     td->td_tiledepth = 1;
  1194.     td->td_grayresponseunit = GRAYRESPONSEUNIT_100S;
  1195.     td->td_resolutionunit = RESUNIT_INCH;
  1196.     td->td_colorresponseunit = COLORRESPONSEUNIT_100S;
  1197.     td->td_datatype = DATATYPE_VOID;
  1198.     td->td_imagedepth = 1;
  1199.     td->td_inkset = INKSET_CMYK;
  1200.     (void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  1201.     /*
  1202.      * NB: The directory is marked dirty as a result of setting
  1203.      * up the default compression scheme.  However, this really
  1204.      * isn't correct -- we want TIFF_DIRTYDIRECT to be set only
  1205.      * if the user does something.  We could just do the setup
  1206.      * by hand, but it seems better to use the normal mechanism
  1207.      * (i.e. TIFFSetField).
  1208.      */
  1209.     tif->tif_flags &= ~TIFF_DIRTYDIRECT;
  1210.     return (1);
  1211. }
  1212.  
  1213. static
  1214. DECLARE2(setString, char**, cpp, char*, cp)
  1215. {
  1216.     if (*cpp)
  1217.         free(*cpp), *cpp = 0;
  1218.     if (cp) {
  1219.         int len = strlen(cp)+1;
  1220.         if (*cpp = malloc(len))
  1221.             bcopy(cp, *cpp, len);
  1222.     }
  1223. }
  1224.  
  1225. static
  1226. DECLARE3(setCurve, u_short**, wpp, u_short*, wp, long, nw)
  1227. {
  1228.     if (*wpp)
  1229.         free((char *)*wpp), *wpp = 0;
  1230.     nw *= sizeof (u_short);
  1231.     if (wp && (*wpp = (u_short *)malloc(nw)))
  1232.         bcopy(wp, *wpp, nw);
  1233. }
  1234.  
  1235. #ifdef notdef
  1236. static
  1237. DECLARE3(setFloatArray, float**, wpp, float*, wp, long, nw)
  1238. {
  1239.     if (*wpp)
  1240.         free((char *)*wpp), *wpp = 0;
  1241.     nw *= sizeof (float);
  1242.     if (wp && (*wpp = (float *)malloc(nw)))
  1243.         bcopy(wp, *wpp, nw);
  1244. }
  1245. #endif
  1246.  
  1247. #ifdef JPEG_SUPPORT
  1248. /*
  1249.  * Install a JPEG Quantization table.
  1250.  * Note that we reorder the elements
  1251.  * of the array in the zig-zag order
  1252.  * that is expected by the compression code
  1253.  * and that is to be stored in the file.
  1254.  */
  1255. static
  1256. DECLARE3(setJPEGQTable, u_short***, wpp, u_short**, wp, int, nc)
  1257. {
  1258.     static u_char zigzag[64] = {
  1259.         0,  1,  5,  6, 14, 15, 27, 28,
  1260.         2,  4,  7, 13, 16, 26, 29, 42,
  1261.         3,  8, 12, 17, 25, 30, 41, 43,
  1262.         9, 11, 18, 24, 31, 40, 44, 53,
  1263.        10, 19, 23, 32, 39, 45, 52, 54,
  1264.        20, 22, 33, 38, 46, 51, 55, 60,
  1265.        21, 34, 37, 47, 50, 56, 59, 61,
  1266.        35, 36, 48, 49, 57, 58, 62, 63
  1267.     };
  1268.     char *tab;
  1269.     int i, j;
  1270.  
  1271.     if (*wpp)
  1272.         free((char *)*wpp), *wpp = 0;
  1273.     *wpp = (u_short **)
  1274.         malloc(nc * (sizeof (u_short *) + 64*sizeof (u_short)));
  1275.     tab = (((char *)*wpp) + nc*sizeof (u_short *));
  1276.     for (i = 0; i < nc; i++) {
  1277.         (*wpp)[i] = (u_short *)tab;
  1278.         for (j = 0; j < 64; j++)
  1279.             (*wpp)[zigzag[j]] = wp[j];
  1280.         tab += 64*sizeof (u_short);
  1281.     }
  1282. }
  1283.  
  1284. /*
  1285.  * Install a JPEG Coefficient table.
  1286.  */
  1287. static
  1288. DECLARE3(setJPEGCTable, u_char***, cpp, u_char**, cp, int, nc)
  1289. {
  1290.     u_char *tab;
  1291.     int i, j, ncodes, nw;
  1292.  
  1293.     if (*cpp)
  1294.         free(*cpp), *cpp = 0;
  1295.     /*
  1296.      * Calculate the size of the table by counting
  1297.      * the number of codes specified in the bits array.
  1298.      */
  1299.     nw = 0;
  1300.     for (i = 0; i < nc; i++) {
  1301.         nw += 16;        /* 16 bytes for bits array */
  1302.         for (j = 0; j < 16; j++)/* sum up count of codes */
  1303.             nw += cp[i][j];
  1304.     }
  1305.     *cpp = (u_char **)malloc(nc*sizeof (u_char *) + nw);
  1306.     tab = ((u_char *)*cpp) + nc*sizeof (u_char *);
  1307.     /*
  1308.      * Setup internal array and copy user data.
  1309.      */
  1310.     for (i = 0; i < nc; i++) {
  1311.         (*cpp)[i] = tab;
  1312.         for (ncodes = 0, j = 0; j < 16; j++)
  1313.             ncodes += tab[j];
  1314.         bcopy(cp[i], (*cpp)[i], ncodes);
  1315.         tab += 16+ncodes;
  1316.     }
  1317. }
  1318. #endif
  1319.  
  1320. static
  1321. TIFFSetField1(tif, tag, ap)
  1322.     TIFF *tif;
  1323.     int tag;
  1324.     va_list ap;
  1325. {
  1326.     static char module[] = "TIFFSetField";
  1327.     TIFFDirectory *td = &tif->tif_dir;
  1328.     long v;
  1329.     int field = -1, status = 1;
  1330.  
  1331.     switch (tag) {
  1332.     case TIFFTAG_SUBFILETYPE:
  1333.         td->td_subfiletype = va_arg(ap, int);
  1334.         field = FIELD_SUBFILETYPE;
  1335.         break;
  1336.     case TIFFTAG_IMAGEWIDTH:
  1337.         td->td_imagewidth = va_arg(ap, u_long);
  1338.         field = FIELD_IMAGEDIMENSIONS;
  1339.         break;
  1340.     case TIFFTAG_IMAGELENGTH:
  1341.         td->td_imagelength = va_arg(ap, u_long);
  1342.         field = FIELD_IMAGEDIMENSIONS;
  1343.         break;
  1344.     case TIFFTAG_BITSPERSAMPLE:
  1345.         td->td_bitspersample = va_arg(ap, int);
  1346.         field = FIELD_BITSPERSAMPLE;
  1347.         break;
  1348.     case TIFFTAG_COMPRESSION:
  1349.         v = va_arg(ap, int) & 0xffff;
  1350.         /*
  1351.          * If we're changing the compression scheme,
  1352.          * the notify the previous module so that it
  1353.          * can cleanup any state it's setup.
  1354.          */
  1355.         if (TIFFFieldSet(tif, FIELD_COMPRESSION)) {
  1356.             if (td->td_compression == v)
  1357.                 break;
  1358.             if (tif->tif_cleanup)
  1359.                 (*tif->tif_cleanup)(tif);
  1360.         }
  1361.         /*
  1362.          * Setup new compression routine state.
  1363.          */
  1364.         if (status = TIFFSetCompressionScheme(tif, v)) {
  1365.             td->td_compression = v;
  1366.             field = FIELD_COMPRESSION;
  1367.         }
  1368.         break;
  1369.     case TIFFTAG_PHOTOMETRIC:
  1370.         td->td_photometric = va_arg(ap, int);
  1371.         field = FIELD_PHOTOMETRIC;
  1372.         break;
  1373.     case TIFFTAG_THRESHHOLDING:
  1374.         td->td_threshholding = va_arg(ap, int);
  1375.         field = FIELD_THRESHHOLDING;
  1376.         break;
  1377.     case TIFFTAG_FILLORDER:
  1378.         td->td_fillorder = va_arg(ap, int);
  1379.         field = FIELD_FILLORDER;
  1380.         break;
  1381.     case TIFFTAG_DOCUMENTNAME:
  1382.         setString(&td->td_documentname, va_arg(ap, char *));
  1383.         field = FIELD_DOCUMENTNAME;
  1384.         break;
  1385.     case TIFFTAG_ARTIST:
  1386.         setString(&td->td_artist, va_arg(ap, char *));
  1387.         field = FIELD_ARTIST;
  1388.         break;
  1389.     case TIFFTAG_DATETIME:
  1390.         setString(&td->td_datetime, va_arg(ap, char *));
  1391.         field = FIELD_DATETIME;
  1392.         break;
  1393.     case TIFFTAG_HOSTCOMPUTER:
  1394.         setString(&td->td_hostcomputer, va_arg(ap, char *));
  1395.         field = FIELD_HOSTCOMPUTER;
  1396.         break;
  1397.     case TIFFTAG_IMAGEDESCRIPTION:
  1398.         setString(&td->td_imagedescription, va_arg(ap, char *));
  1399.         field = FIELD_IMAGEDESCRIPTION;
  1400.         break;
  1401.     case TIFFTAG_MAKE:
  1402.         setString(&td->td_make, va_arg(ap, char *));
  1403.         field = FIELD_MAKE;
  1404.         break;
  1405.     case TIFFTAG_MODEL:
  1406.         setString(&td->td_model, va_arg(ap, char *));
  1407.         field = FIELD_MODEL;
  1408.         break;
  1409.     case TIFFTAG_SOFTWARE:
  1410.         setString(&td->td_software, va_arg(ap, char *));
  1411.         field = FIELD_SOFTWARE;
  1412.         break;
  1413.     case TIFFTAG_ORIENTATION:
  1414.         td->td_orientation = va_arg(ap, int);
  1415.         field = FIELD_ORIENTATION;
  1416.         break;
  1417.     case TIFFTAG_SAMPLESPERPIXEL:
  1418.         v = va_arg(ap, int);
  1419.         if (v == 0)
  1420.             goto badvalue;
  1421.         if (v > 4) {
  1422.             TIFFError(tif->tif_name,
  1423.                 "Cannot handle %d-channel data", v); 
  1424.             goto bad;
  1425.         }
  1426.         td->td_samplesperpixel = v;
  1427.         field = FIELD_SAMPLESPERPIXEL;
  1428.         break;
  1429.     case TIFFTAG_ROWSPERSTRIP:
  1430.         v = va_arg(ap, u_long);
  1431.         if (v == 0)
  1432.             goto badvalue;
  1433.         td->td_rowsperstrip = v;
  1434.         td->td_tilelength = v;
  1435.         td->td_tilewidth = td->td_imagewidth;
  1436.         field = FIELD_ROWSPERSTRIP;
  1437.         break;
  1438.     case TIFFTAG_MINSAMPLEVALUE:
  1439.         td->td_minsamplevalue = va_arg(ap, int) & 0xffff;
  1440.         field = FIELD_MINSAMPLEVALUE;
  1441.         break;
  1442.     case TIFFTAG_MAXSAMPLEVALUE:
  1443.         td->td_maxsamplevalue = va_arg(ap, int) & 0xffff;
  1444.         field = FIELD_MAXSAMPLEVALUE;
  1445.         break;
  1446.     case TIFFTAG_XRESOLUTION:
  1447.         td->td_xresolution = va_arg(ap, dblparam_t);
  1448.         field = FIELD_RESOLUTION;
  1449.         break;
  1450.     case TIFFTAG_YRESOLUTION:
  1451.         td->td_yresolution = va_arg(ap, dblparam_t);
  1452.         field = FIELD_RESOLUTION;
  1453.         break;
  1454.     case TIFFTAG_PLANARCONFIG:
  1455.         v = va_arg(ap, int);
  1456.         td->td_planarconfig = v;
  1457.         field = FIELD_PLANARCONFIG;
  1458.         break;
  1459.     case TIFFTAG_PAGENAME:
  1460.         setString(&td->td_pagename, va_arg(ap, char *));
  1461.         field = FIELD_PAGENAME;
  1462.         break;
  1463.     case TIFFTAG_XPOSITION:
  1464.         td->td_xposition = va_arg(ap, dblparam_t);
  1465.         field = FIELD_POSITION;
  1466.         break;
  1467.     case TIFFTAG_YPOSITION:
  1468.         td->td_yposition = va_arg(ap, dblparam_t);
  1469.         field = FIELD_POSITION;
  1470.         break;
  1471.     case TIFFTAG_GRAYRESPONSEUNIT:
  1472.         td->td_grayresponseunit = va_arg(ap, int);
  1473.         field = FIELD_GRAYRESPONSEUNIT;
  1474.         break;
  1475.     case TIFFTAG_GRAYRESPONSECURVE:
  1476.         setCurve(&td->td_grayresponsecurve,
  1477.             va_arg(ap, u_short *), 1L<<td->td_bitspersample);
  1478.         field = FIELD_GRAYRESPONSECURVE;
  1479.         break;
  1480.     case TIFFTAG_GROUP3OPTIONS:
  1481.         td->td_group3options = va_arg(ap, u_long);
  1482.         field = FIELD_GROUP3OPTIONS;
  1483.         break;
  1484.     case TIFFTAG_GROUP4OPTIONS:
  1485.         td->td_group4options = va_arg(ap, u_long);
  1486.         field = FIELD_GROUP4OPTIONS;
  1487.         break;
  1488.     case TIFFTAG_RESOLUTIONUNIT:
  1489.         td->td_resolutionunit = va_arg(ap, int);
  1490.         field = FIELD_RESOLUTIONUNIT;
  1491.         break;
  1492.     case TIFFTAG_PAGENUMBER:
  1493.         td->td_pagenumber[0] = va_arg(ap, int);
  1494.         td->td_pagenumber[1] = va_arg(ap, int);
  1495.         field = FIELD_PAGENUMBER;
  1496.         break;
  1497.     case TIFFTAG_COLORRESPONSEUNIT:
  1498.         td->td_colorresponseunit = va_arg(ap, int);
  1499.         field = FIELD_COLORRESPONSEUNIT;
  1500.         break;
  1501.     case TIFFTAG_COLORRESPONSECURVE:
  1502.         v = 1L<<td->td_bitspersample;
  1503.         setCurve(&td->td_redresponsecurve, va_arg(ap, u_short *), v);
  1504.         setCurve(&td->td_greenresponsecurve, va_arg(ap, u_short *), v);
  1505.         setCurve(&td->td_blueresponsecurve, va_arg(ap, u_short *), v);
  1506.         field = FIELD_COLORRESPONSECURVE;
  1507.         break;
  1508.     case TIFFTAG_COLORMAP:
  1509.         v = 1L<<td->td_bitspersample;
  1510.         setCurve(&td->td_redcolormap, va_arg(ap, u_short *), v);
  1511.         setCurve(&td->td_greencolormap, va_arg(ap, u_short *), v);
  1512.         setCurve(&td->td_bluecolormap, va_arg(ap, u_short *), v);
  1513.         field = FIELD_COLORMAP;
  1514.         break;
  1515.     case TIFFTAG_PREDICTOR:
  1516.         td->td_predictor = va_arg(ap, int);
  1517.         field = FIELD_PREDICTOR;
  1518.         break;
  1519.     case TIFFTAG_MATTEING:
  1520.         td->td_matteing = va_arg(ap, int);
  1521.         field = FIELD_MATTEING;
  1522.         break;
  1523.     case TIFFTAG_INKSET:
  1524.         td->td_inkset = va_arg(ap, int);
  1525.         field = FIELD_INKSET;
  1526.         break;
  1527.     case TIFFTAG_BADFAXLINES:
  1528.         td->td_badfaxlines = va_arg(ap, u_long);
  1529.         field = FIELD_BADFAXLINES;
  1530.         break;
  1531.     case TIFFTAG_CLEANFAXDATA:
  1532.         td->td_cleanfaxdata = va_arg(ap, int);
  1533.         field = FIELD_CLEANFAXDATA;
  1534.         break;
  1535.     case TIFFTAG_CONSECUTIVEBADFAXLINES:
  1536.         td->td_badfaxrun = va_arg(ap, int);
  1537.         field = FIELD_BADFAXRUN;
  1538.         break;
  1539.     case TIFFTAG_TILEWIDTH:
  1540.         td->td_tilewidth = va_arg(ap, u_long);
  1541.         field = FIELD_TILEDIMENSIONS;
  1542.         tif->tif_flags |= TIFF_ISTILED;
  1543.         break;
  1544.     case TIFFTAG_TILELENGTH:
  1545.         td->td_tilelength = va_arg(ap, u_long);
  1546.         field = FIELD_TILEDIMENSIONS;
  1547.         tif->tif_flags |= TIFF_ISTILED;
  1548.         break;
  1549.     case TIFFTAG_TILEDEPTH:
  1550.         v = va_arg(ap, u_long);
  1551.         if (v == 0)
  1552.             goto badvalue;
  1553.         td->td_tiledepth = v;
  1554.         field = FIELD_TILEDEPTH;
  1555.         break;
  1556.     case TIFFTAG_DATATYPE:
  1557.         td->td_datatype = va_arg(ap, int);
  1558.         field = FIELD_DATATYPE;
  1559.         break;
  1560.     case TIFFTAG_IMAGEDEPTH:
  1561.         td->td_imagedepth = va_arg(ap, u_long);
  1562.         field = FIELD_IMAGEDEPTH;
  1563.         break;
  1564. #ifdef JPEG_SUPPORT
  1565.     case TIFFTAG_JPEGPROC:
  1566.         td->td_jpegproc = va_arg(ap, int);
  1567.         field = FIELD_JPEGPROC;
  1568.         break;
  1569.     case TIFFTAG_JPEGQTABLEPREC:
  1570.         td->td_jpegprec = va_arg(ap, int);
  1571.         field = FIELD_JPEGQTABLEPREC;
  1572.         break;
  1573.     case TIFFTAG_JPEGQTABLES:
  1574.         setJPEGQTable(&td->td_qtab, va_arg(ap, u_short **),
  1575.             td->td_samplesperpixel);
  1576.         field = FIELD_JPEGQTABLES;
  1577.         break;
  1578.     case TIFFTAG_JPEGDCTABLES:
  1579.         setJPEGCTable(&td->td_dctab, va_arg(ap, u_char **),
  1580.             td->td_samplesperpixel);
  1581.         field = FIELD_JPEGDCTABLES;
  1582.         break;
  1583.     case TIFFTAG_JPEGACTABLES:
  1584.         setJPEGCTable(&td->td_actab, va_arg(ap, u_char **),
  1585.             td->td_samplesperpixel);
  1586.         field = FIELD_JPEGACTABLES;
  1587.         break;
  1588. #endif
  1589.     }
  1590.     if (field >= 0) {
  1591.         TIFFSetFieldBit(tif, field);
  1592.         tif->tif_flags |= TIFF_DIRTYDIRECT;
  1593.     }
  1594.     va_end(ap);
  1595.     return (status);
  1596. badvalue:
  1597.     TIFFError(tif->tif_name, "%d: Bad value for \"%s\"", v,
  1598.         FieldWithTag(tag)->field_name);
  1599. bad:
  1600.     va_end(ap);
  1601.     return (0);
  1602. }
  1603.  
  1604. /*
  1605.  * Return 1/0 according to whether or not
  1606.  * it is permissible to set the tag's value.
  1607.  * Note that we allow ImageLength to be changed
  1608.  * so that we can append and extend to images.
  1609.  * Any other tag may not be altered once writing
  1610.  * has commenced, unless its value has no effect
  1611.  * on the format of the data that is written.
  1612.  */
  1613. static
  1614. OkToChangeTag(tif, tag)
  1615.     TIFF *tif;
  1616.     int tag;
  1617. {
  1618.     if (tag != TIFFTAG_IMAGELENGTH &&
  1619.         (tif->tif_flags & TIFF_BEENWRITING)) {
  1620.         TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1621.         /*
  1622.          * Consult info table to see if tag can be changed
  1623.          * after we've started writing.  We only allow changes
  1624.          * to those tags that don't/shouldn't affect the
  1625.          * compression and/or format of the data.
  1626.          */
  1627.         if (fip && !fip->field_oktochange)
  1628.             return (0);
  1629.     }
  1630.     return (1);
  1631. }
  1632.  
  1633. /*
  1634.  * Record the value of a field in the
  1635.  * internal directory structure.  The
  1636.  * field will be written to the file
  1637.  * when/if the directory structure is
  1638.  * updated.
  1639.  */
  1640. /*VARARGS2*/
  1641. DECLARE2V(TIFFSetField, TIFF*, tif, int, tag)
  1642. {
  1643.     int status = 0;
  1644.  
  1645.     if (OkToChangeTag(tif, tag)) {
  1646.         va_list ap;
  1647.  
  1648.         VA_START(ap, tag);
  1649.         status = TIFFSetField1(tif, tag, ap);
  1650.         va_end(ap);
  1651.     } else {
  1652.         TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1653.         if (fip)
  1654.             TIFFError("TIFFSetField",
  1655.                 "%s: Cannot modify tag \"%s\" while writing",
  1656.                 tif->tif_name, fip->field_name);
  1657.     }
  1658.     return (status);
  1659. }
  1660.  
  1661. /*
  1662.  * Like TIFFSetField, but taking a varargs
  1663.  * parameter list.  This routine is useful
  1664.  * for building higher-level interfaces on
  1665.  * top of the library.
  1666.  */
  1667. TIFFVSetField(tif, tag, ap)
  1668.     TIFF *tif;
  1669.     int tag;
  1670.     va_list ap;
  1671. {
  1672.     int status = 0;
  1673.  
  1674.     if (!OkToChangeTag(tif, tag)) {
  1675.         TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1676.         if (fip)
  1677.             TIFFError("TIFFVSetField",
  1678.                 "%s: Cannot modify tag \"%s\" while writing",
  1679.                 tif->tif_name, fip->field_name);
  1680.     } else
  1681.         status = TIFFSetField1(tif, tag, ap);
  1682.     return (status);
  1683. }
  1684.  
  1685. /*
  1686.  * Return the value of a field in the
  1687.  * internal directory structure.
  1688.  */
  1689. /*VARARGS2*/
  1690. DECLARE2V(TIFFGetField, TIFF*, tif, int, tag)
  1691. {
  1692.     TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1693.  
  1694.     if (!fip)
  1695.         TIFFError("TIFFGetField", "Unknown field, tag 0x%x", tag);
  1696.     else if (TIFFFieldSet(tif, fip->field_bit)) {
  1697.         va_list ap;
  1698.  
  1699.         VA_START(ap, tag);
  1700.         (void) TIFFGetField1(&tif->tif_dir, tag, ap);
  1701.         va_end(ap);
  1702.         return (1);
  1703.     }
  1704.     return (0);
  1705. }
  1706.  
  1707. /*
  1708.  * Like TIFFGetField, but taking a varargs
  1709.  * parameter list.  This routine is useful
  1710.  * for building higher-level interfaces on
  1711.  * top of the library.
  1712.  */
  1713. TIFFVGetField(tif, tag, ap)
  1714.     TIFF *tif;
  1715.     int tag;
  1716.     va_list ap;
  1717. {
  1718.     TIFFFieldInfo *fip = FindFieldInfo(tag, TIFF_ANY);
  1719.  
  1720.     if (fip) {
  1721.         if (TIFFFieldSet(tif, fip->field_bit)) {
  1722.             (void) TIFFGetField1(&tif->tif_dir, tag, ap);
  1723.             return (1);
  1724.         }
  1725.     } else
  1726.         TIFFError("TIFFGetField", "Unknown field, tag 0x%x", tag);
  1727.     return (0);
  1728. }
  1729.  
  1730. static
  1731. TIFFGetField1(td, tag, ap)
  1732.     TIFFDirectory *td;
  1733.     int tag;
  1734.     va_list ap;
  1735. {
  1736.  
  1737.     switch (tag) {
  1738.     case TIFFTAG_SUBFILETYPE:
  1739.         *va_arg(ap, u_long *) = td->td_subfiletype;
  1740.         break;
  1741.     case TIFFTAG_IMAGEWIDTH:
  1742.         *va_arg(ap, u_long *) = td->td_imagewidth;
  1743.         break;
  1744.     case TIFFTAG_IMAGELENGTH:
  1745.         *va_arg(ap, u_long *) = td->td_imagelength;
  1746.         break;
  1747.     case TIFFTAG_BITSPERSAMPLE:
  1748.         *va_arg(ap, u_short *) = td->td_bitspersample;
  1749.         break;
  1750.     case TIFFTAG_COMPRESSION:
  1751.         *va_arg(ap, u_short *) = td->td_compression;
  1752.         break;
  1753.     case TIFFTAG_PHOTOMETRIC:
  1754.         *va_arg(ap, u_short *) = td->td_photometric;
  1755.         break;
  1756.     case TIFFTAG_THRESHHOLDING:
  1757.         *va_arg(ap, u_short *) = td->td_threshholding;
  1758.         break;
  1759.     case TIFFTAG_FILLORDER:
  1760.         *va_arg(ap, u_short *) = td->td_fillorder;
  1761.         break;
  1762.     case TIFFTAG_DOCUMENTNAME:
  1763.         *va_arg(ap, char **) = td->td_documentname;
  1764.         break;
  1765.     case TIFFTAG_ARTIST:
  1766.         *va_arg(ap, char **) = td->td_artist;
  1767.         break;
  1768.     case TIFFTAG_DATETIME:
  1769.         *va_arg(ap, char **) = td->td_datetime;
  1770.         break;
  1771.     case TIFFTAG_HOSTCOMPUTER:
  1772.         *va_arg(ap, char **) = td->td_hostcomputer;
  1773.         break;
  1774.     case TIFFTAG_IMAGEDESCRIPTION:
  1775.         *va_arg(ap, char **) = td->td_imagedescription;
  1776.         break;
  1777.     case TIFFTAG_MAKE:
  1778.         *va_arg(ap, char **) = td->td_make;
  1779.         break;
  1780.     case TIFFTAG_MODEL:
  1781.         *va_arg(ap, char **) = td->td_model;
  1782.         break;
  1783.     case TIFFTAG_SOFTWARE:
  1784.         *va_arg(ap, char **) = td->td_software;
  1785.         break;
  1786.     case TIFFTAG_ORIENTATION:
  1787.         *va_arg(ap, u_short *) = td->td_orientation;
  1788.         break;
  1789.     case TIFFTAG_SAMPLESPERPIXEL:
  1790.         *va_arg(ap, u_short *) = td->td_samplesperpixel;
  1791.         break;
  1792.     case TIFFTAG_ROWSPERSTRIP:
  1793.         *va_arg(ap, u_long *) = td->td_rowsperstrip;
  1794.         break;
  1795.     case TIFFTAG_MINSAMPLEVALUE:
  1796.         *va_arg(ap, u_short *) = td->td_minsamplevalue;
  1797.         break;
  1798.     case TIFFTAG_MAXSAMPLEVALUE:
  1799.         *va_arg(ap, u_short *) = td->td_maxsamplevalue;
  1800.         break;
  1801.     case TIFFTAG_XRESOLUTION:
  1802.         *va_arg(ap, float *) = td->td_xresolution;
  1803.         break;
  1804.     case TIFFTAG_YRESOLUTION:
  1805.         *va_arg(ap, float *) = td->td_yresolution;
  1806.         break;
  1807.     case TIFFTAG_PLANARCONFIG:
  1808.         *va_arg(ap, u_short *) = td->td_planarconfig;
  1809.         break;
  1810.     case TIFFTAG_XPOSITION:
  1811.         *va_arg(ap, float *) = td->td_xposition;
  1812.         break;
  1813.     case TIFFTAG_YPOSITION:
  1814.         *va_arg(ap, float *) = td->td_yposition;
  1815.         break;
  1816.     case TIFFTAG_PAGENAME:
  1817.         *va_arg(ap, char **) = td->td_pagename;
  1818.         break;
  1819.     case TIFFTAG_GRAYRESPONSEUNIT:
  1820.         *va_arg(ap, u_short *) = td->td_grayresponseunit;
  1821.         break;
  1822.     case TIFFTAG_GRAYRESPONSECURVE:
  1823.         *va_arg(ap, u_short **) = td->td_grayresponsecurve;
  1824.         break;
  1825.     case TIFFTAG_GROUP3OPTIONS:
  1826.         *va_arg(ap, u_long *) = td->td_group3options;
  1827.         break;
  1828.     case TIFFTAG_GROUP4OPTIONS:
  1829.         *va_arg(ap, u_long *) = td->td_group4options;
  1830.         break;
  1831.     case TIFFTAG_RESOLUTIONUNIT:
  1832.         *va_arg(ap, u_short *) = td->td_resolutionunit;
  1833.         break;
  1834.     case TIFFTAG_PAGENUMBER:
  1835.         *va_arg(ap, u_short *) = td->td_pagenumber[0];
  1836.         *va_arg(ap, u_short *) = td->td_pagenumber[1];
  1837.         break;
  1838.     case TIFFTAG_COLORRESPONSEUNIT:
  1839.         *va_arg(ap, u_short *) = td->td_colorresponseunit;
  1840.         break;
  1841.     case TIFFTAG_COLORRESPONSECURVE:
  1842.         *va_arg(ap, u_short **) = td->td_redresponsecurve;
  1843.         *va_arg(ap, u_short **) = td->td_greenresponsecurve;
  1844.         *va_arg(ap, u_short **) = td->td_blueresponsecurve;
  1845.         break;
  1846.     case TIFFTAG_COLORMAP:
  1847.         *va_arg(ap, u_short **) = td->td_redcolormap;
  1848.         *va_arg(ap, u_short **) = td->td_greencolormap;
  1849.         *va_arg(ap, u_short **) = td->td_bluecolormap;
  1850.         break;
  1851.     case TIFFTAG_PREDICTOR:
  1852.         *va_arg(ap, u_short *) = td->td_predictor;
  1853.         break;
  1854.     case TIFFTAG_STRIPOFFSETS:
  1855.         *va_arg(ap, u_long **) = td->td_stripoffset;
  1856.         break;
  1857.     case TIFFTAG_STRIPBYTECOUNTS:
  1858.         *va_arg(ap, u_long **) = td->td_stripbytecount;
  1859.         break;
  1860.     case TIFFTAG_MATTEING:
  1861.         *va_arg(ap, u_short *) = td->td_matteing;
  1862.         break;
  1863.     case TIFFTAG_INKSET:
  1864.         *va_arg(ap, u_short *) = td->td_inkset;
  1865.         break;
  1866.     case TIFFTAG_BADFAXLINES:
  1867.         *va_arg(ap, u_long *) = td->td_badfaxlines;
  1868.         break;
  1869.     case TIFFTAG_CLEANFAXDATA:
  1870.         *va_arg(ap, u_short *) = td->td_cleanfaxdata;
  1871.         break;
  1872.     case TIFFTAG_CONSECUTIVEBADFAXLINES:
  1873.         *va_arg(ap, u_long *) = td->td_badfaxrun;
  1874.         break;
  1875.     case TIFFTAG_TILEWIDTH:
  1876.         *va_arg(ap, u_long *) = td->td_tilewidth;
  1877.         break;
  1878.     case TIFFTAG_TILELENGTH:
  1879.         *va_arg(ap, u_long *) = td->td_tilelength;
  1880.         break;
  1881.     case TIFFTAG_TILEDEPTH:
  1882.         *va_arg(ap, u_long *) = td->td_tiledepth;
  1883.         break;
  1884.     case TIFFTAG_DATATYPE:
  1885.         *va_arg(ap, u_short *) = td->td_datatype;
  1886.         break;
  1887.     case TIFFTAG_IMAGEDEPTH:
  1888.         *va_arg(ap, u_short *) = td->td_imagedepth;
  1889.         break;
  1890. #ifdef JPEG_SUPPORT
  1891.     case TIFFTAG_JPEGPROC:
  1892.         *va_arg(ap, u_short *) = td->td_jpegproc;
  1893.         break;
  1894.     case TIFFTAG_JPEGQTABLEPREC:
  1895.         *va_arg(ap, u_short *) = td->td_jpegprec;
  1896.         break;
  1897.     case TIFFTAG_JPEGQTABLES:
  1898.         *va_arg(ap, u_short ***) = td->td_qtab;
  1899.         break;
  1900.     case TIFFTAG_JPEGDCTABLES:
  1901.         *va_arg(ap, u_char ***) = td->td_dctab;
  1902.         break;
  1903.     case TIFFTAG_JPEGACTABLES:
  1904.         *va_arg(ap, u_char ***) = td->td_actab;
  1905.         break;
  1906. #endif
  1907.     }
  1908.     va_end(ap);
  1909. }
  1910.  
  1911. /*
  1912.  * Internal interface to TIFFGetField...
  1913.  */
  1914. static
  1915. /*VARARGS2*/
  1916. DECLARE2V(TIFFgetfield, TIFFDirectory*, td, int, tag)
  1917. {
  1918.     va_list ap;
  1919.  
  1920.     VA_START(ap, tag);
  1921.     (void) TIFFGetField1(td, tag, ap);
  1922.     va_end(ap);
  1923. }
  1924.  
  1925. #if USE_PROTOTYPES
  1926. static    TIFFSetupShortLong(TIFF *, TIFFDirEntry *, u_short, u_long);
  1927. static    TIFFWriteRational(TIFF *, u_short, TIFFDirEntry *, float);
  1928. static    TIFFWritePerSampleShorts(TIFF *, u_short, TIFFDirEntry *, short);
  1929. static    TIFFWriteStripThing(TIFF *, u_short, TIFFDirEntry *, u_long *);
  1930. #ifdef JPEG_SUPPORT
  1931. static    TIFFWriteJPEGQTables(TIFF *, TIFFDirEntry *);
  1932. static    TIFFWriteJPEGCTables(TIFF *, u_short, TIFFDirEntry *, u_char **);
  1933. #endif
  1934. static    TIFFWriteData(TIFF *, TIFFDirEntry *, char *);
  1935. static    TIFFLinkDirectory(TIFF *);
  1936. #else
  1937. static    TIFFSetupShortLong();
  1938. static    TIFFWriteRational();
  1939. static    TIFFWritePerSampleShorts();
  1940. static    TIFFWriteStripThing();
  1941. #ifdef JPEG_SUPPORT
  1942. static    TIFFWriteJPEGQTables();
  1943. static    TIFFWriteJPEGCTables();
  1944. #endif
  1945. static    TIFFWriteData();
  1946. static    TIFFLinkDirectory();
  1947. #endif
  1948.  
  1949. #define    WriteRationalPair(tag1, v1, tag2, v2) \
  1950.     (TIFFWriteRational(tif, tag1, dir++, v1) && \
  1951.      TIFFWriteRational(tif, tag2, dir++, v2))
  1952.  
  1953. static    long dataoff;
  1954. /*
  1955.  * Write the contents of the current directory
  1956.  * to the specified file.  This routine doesn't
  1957.  * handle overwriting a directory with auxiliary
  1958.  * storage that's been changed.
  1959.  */
  1960. TIFFWriteDirectory(tif)
  1961.     TIFF *tif;
  1962. {
  1963.     short dircount, v;
  1964.     int nfields, dirsize;
  1965.     char *data, *cp;
  1966.     TIFFFieldInfo *fip;
  1967.     TIFFDirEntry *dir;
  1968.     TIFFDirectory *td;
  1969.     u_long b, off, fields[sizeof (td->td_fieldsset) / sizeof (u_long)];
  1970.  
  1971.     if (tif->tif_mode == O_RDONLY)
  1972.         return (1);
  1973.     /*
  1974.      * Clear write state so that subsequent images with
  1975.      * different characteristics get the right buffers
  1976.      * setup for them.
  1977.      */
  1978.     if (tif->tif_close)
  1979.         (*tif->tif_close)(tif);
  1980.     if (tif->tif_cleanup)
  1981.         (*tif->tif_cleanup)(tif);
  1982.     /*
  1983.      * Flush any data that might have been written
  1984.      * by the compression close+cleanup routines.
  1985.      */
  1986.     if (tif->tif_rawcc > 0 && !TIFFFlushData1(tif)) {
  1987.         TIFFError(tif->tif_name,
  1988.             "Error flushing data before directory write");
  1989.         return (0);
  1990.     }
  1991.     if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
  1992.         free(tif->tif_rawdata);
  1993.         tif->tif_rawdata = NULL;
  1994.         tif->tif_rawcc = 0;
  1995.     }
  1996.     tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP);
  1997.  
  1998.     td = &tif->tif_dir;
  1999.     /*
  2000.      * Size the directory so that we can calculate
  2001.      * offsets for the data items that aren't kept
  2002.      * in-place in each field.
  2003.      */
  2004.     nfields = 0;
  2005.     for (b = 0; b <= FIELD_LAST; b++)
  2006.         if (TIFFFieldSet(tif, b))
  2007.             nfields += (b < FIELD_SUBFILETYPE ? 2 : 1);
  2008.     dirsize = nfields * sizeof (TIFFDirEntry);
  2009.     data = malloc(dirsize);
  2010.     if (data == NULL) {
  2011.         TIFFError(tif->tif_name,
  2012.             "Cannot write directory, out of space");
  2013.         return (0);
  2014.     }
  2015.     /*
  2016.      * Directory hasn't been placed yet, put
  2017.      * it at the end of the file and link it
  2018.      * into the existing directory structure.
  2019.      */
  2020.     if (tif->tif_diroff == 0 && !TIFFLinkDirectory(tif))
  2021.         return (0);
  2022.     dataoff = tif->tif_diroff + sizeof (short) + dirsize + sizeof (long);
  2023.     if (dataoff & 1)
  2024.         dataoff++;
  2025.     (void) lseek(tif->tif_fd, dataoff, L_SET);
  2026.     dir = (TIFFDirEntry *)data;
  2027.     /*
  2028.      * Setup external form of directory
  2029.      * entries and write data items.
  2030.      */
  2031.     bcopy(td->td_fieldsset, fields, sizeof (fields));
  2032.     for (fip = FieldInfo; fip < &FieldInfo[NFIELDINFO]; fip++) {
  2033.         if (fip->field_bit == (u_short)-1 ||
  2034.             !FieldSet(fields, fip->field_bit))
  2035.             continue;
  2036.         if (fip->field_type == TIFF_ASCII) {
  2037.             TIFFgetfield(td, fip->field_tag, &cp);
  2038.             dir->tdir_tag = fip->field_tag;
  2039.             dir->tdir_type = (short)TIFF_ASCII;
  2040.             dir->tdir_count = strlen(cp) + 1;
  2041.             if (!TIFFWriteData(tif, dir++, cp))
  2042.                 goto bad;
  2043.             ResetFieldBit(fields, fip->field_bit);
  2044.             continue;
  2045.         }
  2046.         switch (fip->field_bit) {
  2047.         case FIELD_STRIPOFFSETS:
  2048.         case FIELD_STRIPBYTECOUNTS:
  2049.             if (!TIFFWriteStripThing(tif,
  2050.                 fip->field_tag, dir++,
  2051.                 fip->field_bit == FIELD_STRIPOFFSETS ?
  2052.                   td->td_stripoffset : td->td_stripbytecount))
  2053.                 goto bad;
  2054.             break;
  2055.         case FIELD_GRAYRESPONSECURVE:
  2056.             dir->tdir_tag = fip->field_tag;
  2057.             dir->tdir_type = (short)TIFF_SHORT;
  2058.             dir->tdir_count = 1L<<td->td_bitspersample;
  2059. #define    WRITE(x)    TIFFWriteData(tif, dir, (char*) x)
  2060.             if (!WRITE(td->td_grayresponsecurve))
  2061.                 goto bad;
  2062.             dir++;
  2063.             break;
  2064.         case FIELD_COLORRESPONSECURVE:
  2065.         case FIELD_COLORMAP:
  2066.             dir->tdir_tag = fip->field_tag;
  2067.             dir->tdir_type = (short)TIFF_SHORT;
  2068.             /* XXX -- yech, fool TIFFWriteData */
  2069.             dir->tdir_count = 1L<<td->td_bitspersample;
  2070.             off = dataoff;
  2071.             if (fip->field_tag == TIFFTAG_COLORMAP) {
  2072.                 if (!WRITE(td->td_redcolormap) ||
  2073.                     !WRITE(td->td_greencolormap) ||
  2074.                     !WRITE(td->td_bluecolormap))
  2075.                     goto bad;
  2076.             } else {
  2077.                 if (!WRITE(td->td_redresponsecurve) ||
  2078.                     !WRITE(td->td_greenresponsecurve) ||
  2079.                     !WRITE(td->td_blueresponsecurve))
  2080.                     goto bad;
  2081.             }
  2082. #undef WRITE
  2083.             dir->tdir_count *= 3;
  2084.             dir->tdir_offset = off;
  2085.             dir++;
  2086.             break;
  2087.         case FIELD_IMAGEDIMENSIONS:
  2088.             TIFFSetupShortLong(tif, dir++,
  2089.                 TIFFTAG_IMAGEWIDTH, td->td_imagewidth);
  2090.             TIFFSetupShortLong(tif, dir++,
  2091.                 TIFFTAG_IMAGELENGTH, td->td_imagelength);
  2092.             break;
  2093.         case FIELD_TILEDIMENSIONS:
  2094.             TIFFSetupShortLong(tif, dir++,
  2095.                 TIFFTAG_TILEWIDTH, td->td_tilewidth);
  2096.             TIFFSetupShortLong(tif, dir++,
  2097.                 TIFFTAG_TILELENGTH, td->td_tilelength);
  2098.             break;
  2099.         case FIELD_POSITION:
  2100.             if (!WriteRationalPair(
  2101.                 TIFFTAG_XPOSITION, td->td_xposition,
  2102.                 TIFFTAG_YPOSITION, td->td_yposition))
  2103.                 goto bad;
  2104.             break;
  2105.         case FIELD_RESOLUTION:
  2106.             if (!WriteRationalPair(
  2107.                 TIFFTAG_XRESOLUTION, td->td_xresolution,
  2108.                 TIFFTAG_YRESOLUTION, td->td_yresolution))
  2109.                 goto bad;
  2110.             break;
  2111.         case FIELD_BITSPERSAMPLE:
  2112.         case FIELD_MINSAMPLEVALUE:
  2113.         case FIELD_MAXSAMPLEVALUE:
  2114.         case FIELD_DATATYPE:
  2115.             TIFFgetfield(td, fip->field_tag, &v);
  2116.             if (!TIFFWritePerSampleShorts(tif, fip->field_tag,
  2117.                 dir++, v))
  2118.                 goto bad;
  2119.             break;
  2120.         case FIELD_PAGENUMBER: {
  2121.             short v1, v2;
  2122.             dir->tdir_tag = TIFFTAG_PAGENUMBER;
  2123.             dir->tdir_type = (short)TIFF_SHORT;
  2124.             dir->tdir_count = 2;
  2125.             TIFFgetfield(td, TIFFTAG_PAGENUMBER, &v1, &v2);
  2126.             if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN)
  2127.                 dir->tdir_offset = (v1 << 16) | (v2 & 0xffff);
  2128.             else
  2129.                 dir->tdir_offset = (v2 << 16) | (v1 & 0xffff);
  2130.             dir++;
  2131.             break;
  2132. #ifdef JPEG_SUPPORT
  2133.         case FIELD_JPEGQTABLES:
  2134.             if (!TIFFWriteJPEGQTables(tif, dir))
  2135.                 goto bad;
  2136.             break;
  2137.         case FIELD_JPEGDCTABLES:
  2138.             if (!TIFFWriteJPEGCTables(tif,
  2139.                 TIFFTAG_JPEGDCTABLES, dir, td->td_dctab))
  2140.                 goto bad;
  2141.             break;
  2142.         case FIELD_JPEGACTABLES:
  2143.             if (!TIFFWriteJPEGCTables(tif,
  2144.                 TIFFTAG_JPEGACTABLES, dir, td->td_actab))
  2145.                 goto bad;
  2146.             break;
  2147. #endif
  2148.         }
  2149.         default:
  2150.             dir->tdir_tag = fip->field_tag;
  2151.             dir->tdir_type = (u_short)fip->field_type;
  2152.             dir->tdir_count = fip->field_count;
  2153.             if (fip->field_type == TIFF_SHORT) {
  2154.                 TIFFgetfield(td, fip->field_tag, &v);
  2155.                 dir->tdir_offset =
  2156.                     TIFFInsertData(tif, dir->tdir_type, v);
  2157.             } else
  2158.                 TIFFgetfield(td, fip->field_tag,
  2159.                     &dir->tdir_offset);
  2160.             dir++;
  2161.             break;
  2162.         }
  2163.         ResetFieldBit(fields, fip->field_bit);
  2164.     }
  2165.     /*
  2166.      * Write directory.
  2167.      */
  2168.     (void) lseek(tif->tif_fd, tif->tif_diroff, L_SET);
  2169.     dircount = nfields;
  2170.     if (!WriteOK(tif->tif_fd, &dircount, sizeof (short))) {
  2171.         TIFFError(tif->tif_name, "Error writing directory count");
  2172.         goto bad;
  2173.     }
  2174.     if (!WriteOK(tif->tif_fd, data, dirsize)) {
  2175.         TIFFError(tif->tif_name, "Error writing directory contents");
  2176.         goto bad;
  2177.     }
  2178.     if (!WriteOK(tif->tif_fd, &tif->tif_nextdiroff, sizeof (long))) {
  2179.         TIFFError(tif->tif_name, "Error writing directory link");
  2180.         goto bad;
  2181.     }
  2182.     TIFFFreeDirectory(tif);
  2183.     free(data);
  2184.     tif->tif_flags &= ~TIFF_DIRTYDIRECT;
  2185.  
  2186.     /*
  2187.      * Reset directory-related state for subsequent
  2188.      * directories.
  2189.      */
  2190.     TIFFDefaultDirectory(tif);
  2191.     tif->tif_diroff = 0;
  2192.     tif->tif_curoff = 0;
  2193.     tif->tif_row = -1;
  2194.     tif->tif_curstrip = -1;
  2195.     return (1);
  2196. bad:
  2197.     free(data);
  2198.     return (0);
  2199. }
  2200. #undef WriteRationalPair
  2201.  
  2202. /*
  2203.  * Setup a directory entry with either a SHORT
  2204.  * or LONG type according to the value.
  2205.  */
  2206. static
  2207. DECLARE4(TIFFSetupShortLong,
  2208.     TIFF*, tif, TIFFDirEntry*, dir, u_short, tag, u_long, v)
  2209. {
  2210.     dir->tdir_tag = tag;
  2211.     dir->tdir_count = 1;
  2212.     if (v > 0xffffL) {
  2213.         dir->tdir_type = (short)TIFF_LONG;
  2214.         dir->tdir_offset = v;
  2215.     } else {
  2216.         dir->tdir_type = (short)TIFF_SHORT;
  2217.         dir->tdir_offset = TIFFInsertData(tif, (int)TIFF_SHORT, v);
  2218.     }
  2219. }
  2220. #undef MakeShortDirent
  2221.  
  2222. /*
  2223.  * Setup a RATIONAL directory entry and
  2224.  * write the associated indirect value.
  2225.  */
  2226. static
  2227. DECLARE4(TIFFWriteRational,
  2228.     TIFF*, tif, u_short, tag, TIFFDirEntry*, dir, float, v)
  2229. {
  2230.     long t[2];
  2231.  
  2232.     dir->tdir_tag = tag;
  2233.     dir->tdir_type = (short)TIFF_RATIONAL;
  2234.     dir->tdir_count = 1;
  2235.     /* need algorithm to convert ... XXX */
  2236.     t[0] = v * 10000.0;
  2237.     t[1] = 10000;
  2238.     return (TIFFWriteData(tif, dir, (char *)t));
  2239. }
  2240.  
  2241. /*
  2242.  * Setup a directory entry that references a
  2243.  * samples/pixel array of SHORT values and
  2244.  * (potentially) write the associated indirect
  2245.  * values.
  2246.  */
  2247. static
  2248. DECLARE4(TIFFWritePerSampleShorts,
  2249.     TIFF*, tif, u_short, tag, TIFFDirEntry*, dir, short, v)
  2250. {
  2251.     short w[4];
  2252.     int i, samplesperpixel = tif->tif_dir.td_samplesperpixel;
  2253.  
  2254.     dir->tdir_tag = tag;
  2255.     dir->tdir_type = (short)TIFF_SHORT;
  2256.     dir->tdir_count = samplesperpixel;
  2257.     if (samplesperpixel <= 2) {
  2258.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  2259.             dir->tdir_offset = (long)v << 16;
  2260.             if (samplesperpixel == 2)
  2261.                 dir->tdir_offset |= v & 0xffff;
  2262.         } else {
  2263.             dir->tdir_offset = v & 0xffff;
  2264.             if (samplesperpixel == 2)
  2265.                 dir->tdir_offset |= (long)v << 16;
  2266.         }
  2267.         return (1);
  2268.     }
  2269.     for (i = 0; i < samplesperpixel; i++)
  2270.         w[i] = v;
  2271.     return (TIFFWriteData(tif, dir, (char *)w));
  2272. }
  2273.  
  2274. /*
  2275.  * Setup a directory entry of strip or
  2276.  * tile offsets or lengths and write the
  2277.  * associated indirect values.
  2278.  */
  2279. static
  2280. DECLARE4(TIFFWriteStripThing,
  2281.     TIFF*, tif, u_short, tag, TIFFDirEntry*, dir, u_long*, lp)
  2282. {
  2283.  
  2284.     dir->tdir_tag = tag;
  2285.     dir->tdir_type = (short)TIFF_LONG;        /* XXX */
  2286.     dir->tdir_count = tif->tif_dir.td_nstrips;
  2287.     if (dir->tdir_count > 1)
  2288.         return (TIFFWriteData(tif, dir, (char *)lp));
  2289.     dir->tdir_offset = *lp;
  2290.     return (1);
  2291. }
  2292.  
  2293. #ifdef JPEG_SUPPORT
  2294. /*
  2295.  * Setup a directory entry for JPEG Quantization
  2296.  * tables and write the associated indirect values.
  2297.  */
  2298. static
  2299. DECLARE2(TIFFWriteJPEGQTables, TIFF*, tif, TIFFDirEntry*, dir)
  2300. {
  2301.     TIFFDirectory *td = &tif->tif_dir;
  2302.     TIFFDirEntry tdir;
  2303.     u_short **qtab;
  2304.     u_long off[4];
  2305.     int i;
  2306.  
  2307.     dir->tdir_tag = TIFFTAG_JPEGQTABLES;
  2308.     dir->tdir_type = (short)TIFF_LONG;
  2309.     dir->tdir_count = td->td_samplesperpixel;
  2310.     qtab = td->td_qtab;
  2311.     tdir.tdir_tag = TIFFTAG_JPEGQTABLES;    /* for diagnostics */
  2312.     tdir.tdir_type = (short)
  2313.         (td->td_jpegprec == JPEGQTABLEPREC_8BIT ? TIFF_BYTE : TIFF_SHORT);
  2314.     tdir.tdir_count = 64;
  2315.     for (i = 0; i < dir->tdir_count; i++) {
  2316.         if (tdir.tdir_type == TIFF_BYTE) {
  2317.             char v[64];
  2318.             int j;
  2319.  
  2320.             for (j = 0; j < 64; j++)
  2321.                 v[j] = qtab[i][j];
  2322.             if (!TIFFWriteData(tif, &tdir, v))
  2323.                 return (0);
  2324.         } else if (!TIFFWriteData(tif, &tdir, (char *)qtab[i]))
  2325.             return (0);
  2326.         off[i] = tdir.tdir_offset;
  2327.     }
  2328.     return (TIFFWriteData(tif, dir, (char *)off));
  2329. }
  2330.  
  2331. /*
  2332.  * Setup a directory entry for JPEG Coefficient
  2333.  * tables and write the associated indirect values.
  2334.  */
  2335. static
  2336. DECLARE4(TIFFWriteJPEGCTables,
  2337.     TIFF*, tif, u_short, tag, TIFFDirEntry*, dir, u_char **, tab)
  2338. {
  2339.     TIFFDirectory *td = &tif->tif_dir;
  2340.     TIFFDirEntry tdir;
  2341.     u_long off[4];
  2342.     int i, j, ncodes;
  2343.  
  2344.     dir->tdir_tag = tag;
  2345.     dir->tdir_type = (short)TIFF_LONG;
  2346.     dir->tdir_count = td->td_samplesperpixel;
  2347.     tdir.tdir_tag = tag;        /* for diagnostics */
  2348.     tdir.tdir_type = (short)TIFF_BYTE;
  2349.     for (i = 0; i < dir->tdir_count; i++) {
  2350.         for (ncodes = 0, j = 0; j < 16; j++)
  2351.             ncodes += tab[i][j];
  2352.         tdir.tdir_count = 16+ncodes;
  2353.         if (!TIFFWriteData(tif, &tdir, (char *)tab[i]))
  2354.             return (0);
  2355.         off[i] = tdir.tdir_offset;
  2356.     }
  2357.     return (TIFFWriteData(tif, dir, (char *)off));
  2358. }
  2359. #endif
  2360.  
  2361. /*
  2362.  * Write a contiguous directory item.
  2363.  */
  2364. static
  2365. TIFFWriteData(tif, dir, cp)
  2366.     TIFF *tif;
  2367.     TIFFDirEntry *dir;
  2368.     char *cp;
  2369. {
  2370.     int cc;
  2371.  
  2372.     dir->tdir_offset = dataoff;
  2373.     cc = dir->tdir_count * datawidth[dir->tdir_type];
  2374.     if (SeekOK(tif->tif_fd, dir->tdir_offset) &&
  2375.         WriteOK(tif->tif_fd, cp, cc)) {
  2376.         dataoff += (cc + 1) & ~1;
  2377.         return (1);
  2378.     }
  2379.     TIFFError(tif->tif_name, "Error writing data for field \"%s\"",
  2380.         FieldWithTag(dir->tdir_tag)->field_name);
  2381.     return (0);
  2382. }
  2383.  
  2384. /*
  2385.  * Link the current directory into the
  2386.  * directory chain for the file.
  2387.  */
  2388. static
  2389. TIFFLinkDirectory(tif)
  2390.     register TIFF *tif;
  2391. {
  2392.     static char module[] = "TIFFLinkDirectory";
  2393.     u_short dircount;
  2394.     long nextdir;
  2395.  
  2396.     tif->tif_diroff = (lseek(tif->tif_fd, 0L, L_XTND)+1) &~ 1L;
  2397.     if (tif->tif_header.tiff_diroff == 0) {
  2398.         /*
  2399.          * First directory, overwrite header.
  2400.          */
  2401.         tif->tif_header.tiff_diroff = tif->tif_diroff;
  2402.         (void) lseek(tif->tif_fd, 0L, L_SET);
  2403.         if (!WriteOK(tif->tif_fd, &tif->tif_header,
  2404.             sizeof (tif->tif_header))) {
  2405.             TIFFError(tif->tif_name, "Error writing TIFF header");
  2406.             return (0);
  2407.         }
  2408.         return (1);
  2409.     }
  2410.     /*
  2411.      * Not the first directory, search to the last and append.
  2412.      */
  2413.     nextdir = tif->tif_header.tiff_diroff;
  2414.     do {
  2415.         if (!SeekOK(tif->tif_fd, nextdir) ||
  2416.             !ReadOK(tif->tif_fd, &dircount, sizeof (dircount))) {
  2417.             TIFFError(module, "Error fetching directory count");
  2418.             return (0);
  2419.         }
  2420.         if (tif->tif_flags & TIFF_SWAB)
  2421.             TIFFSwabShort(&dircount);
  2422.         lseek(tif->tif_fd, dircount * sizeof (TIFFDirEntry), L_INCR);
  2423.         if (!ReadOK(tif->tif_fd, &nextdir, sizeof (nextdir))) {
  2424.             TIFFError(module, "Error fetching directory link");
  2425.             return (0);
  2426.         }
  2427.         if (tif->tif_flags & TIFF_SWAB)
  2428.             TIFFSwabLong((u_long *)&nextdir);
  2429.     } while (nextdir != 0);
  2430.     (void) lseek(tif->tif_fd, -sizeof (nextdir), L_INCR);
  2431.     if (!WriteOK(tif->tif_fd, &tif->tif_diroff, sizeof (tif->tif_diroff))) {
  2432.         TIFFError(module, "Error writing directory link");
  2433.         return (0);
  2434.     }
  2435.     return (1);
  2436. }
  2437.  
  2438. /*
  2439.  * Set the n-th directory as the current directory.
  2440.  * NB: Directories are numbered starting at 0.
  2441.  */
  2442. TIFFSetDirectory(tif, n)
  2443.     register TIFF *tif;
  2444.     int n;
  2445. {
  2446.     static char module[] = "TIFFSetDirectory";
  2447.     u_short dircount;
  2448.     long nextdir;
  2449.  
  2450.     nextdir = tif->tif_header.tiff_diroff;
  2451.     while (n-- > 0 && nextdir != 0) {
  2452.         if (!SeekOK(tif->tif_fd, nextdir) ||
  2453.             !ReadOK(tif->tif_fd, &dircount, sizeof (dircount))) {
  2454.             TIFFError(module, "%s: Error fetching directory count",
  2455.                 tif->tif_name);
  2456.             return (0);
  2457.         }
  2458.         if (tif->tif_flags & TIFF_SWAB)
  2459.             TIFFSwabShort(&dircount);
  2460.         lseek(tif->tif_fd, dircount*sizeof (TIFFDirEntry), L_INCR);
  2461.         if (!ReadOK(tif->tif_fd, &nextdir, sizeof (nextdir))) {
  2462.             TIFFError(module, "%s: Error fetching directory link",
  2463.                 tif->tif_name);
  2464.             return (0);
  2465.         }
  2466.         if (tif->tif_flags & TIFF_SWAB)
  2467.             TIFFSwabLong((u_long *)&nextdir);
  2468.     }
  2469.     tif->tif_nextdiroff = nextdir;
  2470.     return (TIFFReadDirectory(tif));
  2471. }
  2472.